<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="刘清政">
  <meta name="keyword" content="hexo-theme">
  
    <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
      db/Mongodb系列/Mongodb快速入门 | Justin-刘清政的博客
    
  </title>
  <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/css/plugins/gitment.css">

  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.js"></script>
  
    
<script src="/js/qrious.js"></script>

  
  
    
<script src="/js/gitment.js"></script>

  
  

  
<meta name="generator" content="Hexo 4.2.0"></head>
<div class="wechat-share">
  <img src="/css/images/logo.png" />
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>Justin-刘清政的博客</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">主页</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">标签</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">归档</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">关于我</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">主页</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">标签</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">归档</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">关于我</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>db/Mongodb系列/Mongodb快速入门</h2>



  <p class="post-date">2020-04-01</p>
    <!-- 不蒜子统计 -->
    <span id="busuanzi_container_page_pv" style='display:none' class="">
        <i class="icon-smile icon"></i> 阅读数：<span id="busuanzi_value_page_pv"></span>次
    </span>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><h1 id="Mongodb"><a href="#Mongodb" class="headerlink" title="Mongodb"></a>Mongodb</h1><h2 id="一-简介"><a href="#一-简介" class="headerlink" title="一 简介"></a>一 简介</h2><p>MongoDB是一款强大、灵活、且易于扩展的通用型数据库</p>
<h3 id="1-1-易用性"><a href="#1-1-易用性" class="headerlink" title="1.1 易用性"></a>1.1 易用性</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">MongoDB是一个面向文档（document-oriented）的数据库，而不是关系型数据库。</span><br><span class="line">不采用关系型主要是为了获得更好得扩展性。当然还有一些其他好处，与关系数据库相比，面向文档的数据库不再有“行“（row）的概念取而代之的是更为灵活的“文档”（document）模型。</span><br><span class="line">通过在文档中嵌入文档和数组，面向文档的方法能够仅使用一条记录来表现复杂的层级关系，这与现代的面向对象语言的开发者对数据的看法一致。</span><br><span class="line">另外，不再有预定义模式（predefined schema）：文档的键（key）和值（value）不再是固定的类型和大小。由于没有固定的模式，根据需要添加或删除字段变得更容易了。通常由于开发者能够进行快速迭代，所以开发进程得以加快。而且，实验更容易进行。开发者能尝试大量的数据模型，从中选一个最好的。</span><br></pre></td></tr></table></figure>

<h3 id="1-2-易扩展性"><a href="#1-2-易扩展性" class="headerlink" title="1.2 易扩展性"></a>1.2 易扩展性</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">应用程序数据集的大小正在以不可思议的速度增长。随着可用带宽的增长和存储器价格的下降，即使是一个小规模的应用程序，需要存储的数据量也可能大的惊人，甚至超出</span><br><span class="line">了很多数据库的处理能力。过去非常罕见的T级数据，现在已经是司空见惯了。</span><br><span class="line">由于需要存储的数据量不断增长，开发者面临一个问题：应该如何扩展数据库，分为纵向扩展和横向扩展，纵向扩展是最省力的做法，但缺点是大型机一般都非常贵，而且</span><br><span class="line">当数据量达到机器的物理极限时，花再多的钱也买不到更强的机器了，此时选择横向扩展更为合适，但横向扩展带来的另外一个问题就是需要管理的机器太多。</span><br><span class="line">MongoDB的设计采用横向扩展。面向文档的数据模型使它能很容易地在多台服务器之间进行数据分割。MongoDB能够自动处理跨集群的数据和负载，自动重新分配文档，以及将</span><br><span class="line">用户的请求路由到正确的机器上。这样，开发者能够集中精力编写应用程序，而不需要考虑如何扩展的问题。如果一个集群需要更大的容量，只需要向集群添加新服务器，MongoDB就会自动将现有的数据向新服务器传送</span><br></pre></td></tr></table></figure>

<h3 id="1-3-丰富的功能"><a href="#1-3-丰富的功能" class="headerlink" title="1.3 丰富的功能"></a>1.3 丰富的功能</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">MongoDB作为一款通用型数据库，除了能够创建、读取、更新和删除数据之外，还提供了一系列不断扩展的独特功能</span><br><span class="line"><span class="comment">#1、索引</span></span><br><span class="line">支持通用二级索引，允许多种快速查询，且提供唯一索引、复合索引、地理空间索引、全文索引</span><br><span class="line"></span><br><span class="line"><span class="comment">#2、聚合</span></span><br><span class="line">支持聚合管道，用户能通过简单的片段创建复杂的集合，并通过数据库自动优化</span><br><span class="line"></span><br><span class="line"><span class="comment">#3、特殊的集合类型</span></span><br><span class="line">支持存在时间有限的集合，适用于那些将在某个时刻过期的数据，如会话session。类似地，MongoDB也支持固定大小的集合，用于保存近期数据，如日志</span><br><span class="line"></span><br><span class="line"><span class="comment">#4、文件存储</span></span><br><span class="line">支持一种非常易用的协议，用于存储大文件和文件元数据。MongoDB并不具备一些在关系型数据库中很普遍的功能，如链接join和复杂的多行事务。省略</span><br><span class="line">这些的功能是处于架构上的考虑，或者说为了得到更好的扩展性，因为在分布式系统中这两个功能难以高效地实现</span><br></pre></td></tr></table></figure>

<h3 id="1-4、卓越的性能"><a href="#1-4、卓越的性能" class="headerlink" title="1.4、卓越的性能"></a>1.4、卓越的性能</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">MongoDB的一个主要目标是提供卓越的性能，这很大程度上决定了MongoDB的设计。MongoDB把尽可能多的内存用作缓存cache，视图为每次查询自动选择正确的索引。</span><br><span class="line">总之各方面的设计都旨在保持它的高性能</span><br><span class="line">虽然MongoDB非常强大并试图保留关系型数据库的很多特性，但它并不追求具备关系型数据库的所有功能。只要有可能，数据库服务器就会将处理逻辑交给客户端。这种精简方式的设计是MongoDB能够实现如此高性能的原因之一</span><br></pre></td></tr></table></figure>

<h2 id="二-MongoDB基础知识"><a href="#二-MongoDB基础知识" class="headerlink" title="二 MongoDB基础知识"></a>二 MongoDB基础知识</h2><p><img src="https://tva1.sinaimg.cn/large/00831rSTly1gdelvcm1snj311o0gsq6o.jpg" alt="image-20200401215128936"></p>
<h3 id="2-1-文档是MongoDB的核心概念。文档就是键值对的一个有序集-‘msg’-’hello’-’foo’-3-。类似于python中的有序字典。"><a href="#2-1-文档是MongoDB的核心概念。文档就是键值对的一个有序集-‘msg’-’hello’-’foo’-3-。类似于python中的有序字典。" class="headerlink" title="2.1 文档是MongoDB的核心概念。文档就是键值对的一个有序集{‘msg’:’hello’,’foo’:3}。类似于python中的有序字典。"></a>2.1 文档是MongoDB的核心概念。文档就是键值对的一个有序集{‘msg’:’hello’,’foo’:3}。类似于python中的有序字典。</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">需要注意的是：</span><br><span class="line"><span class="comment">#1、文档中的键/值对是有序的。</span></span><br><span class="line"><span class="comment">#2、文档中的值不仅可以是在双引号里面的字符串，还可以是其他几种数据类型（甚至可以是整个嵌入的文档)。</span></span><br><span class="line"><span class="comment">#3、MongoDB区分类型和大小写。</span></span><br><span class="line"><span class="comment">#4、MongoDB的文档不能有重复的键。</span></span><br><span class="line"><span class="comment">#5、文档中的值可以是多种不同的数据类型，也可以是一个完整的内嵌文档。文档的键是字符串。除了少数例外情况，键可以使用任意UTF-8字符。</span></span><br><span class="line"></span><br><span class="line">文档键命名规范：</span><br><span class="line"><span class="comment">#1、键不能含有\0 (空字符)。这个字符用来表示键的结尾。</span></span><br><span class="line"><span class="comment">#2、.和$有特别的意义，只有在特定环境下才能使用。</span></span><br><span class="line"><span class="comment">#3、以下划线"_"开头的键是保留的(不是严格要求的)。</span></span><br></pre></td></tr></table></figure>

<h3 id="2-2-集合就是一组文档。如果将MongoDB中的一个文档比喻为关系型数据的一行，那么一个集合就是相当于一张表"><a href="#2-2-集合就是一组文档。如果将MongoDB中的一个文档比喻为关系型数据的一行，那么一个集合就是相当于一张表" class="headerlink" title="2.2 集合就是一组文档。如果将MongoDB中的一个文档比喻为关系型数据的一行，那么一个集合就是相当于一张表"></a>2.2 集合就是一组文档。如果将MongoDB中的一个文档比喻为关系型数据的一行，那么一个集合就是相当于一张表</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#1、集合存在于数据库中，通常情况下为了方便管理，不同格式和类型的数据应该插入到不同的集合，但其实集合没有固定的结构，这意味着我们完全可以把不同格式和类型的数据统统插入一个集合中。</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#2、组织子集合的方式就是使用“.”，分隔不同命名空间的子集合。</span></span><br><span class="line">比如一个具有博客功能的应用可能包含两个集合，分别是blog.posts和blog.authors，这是为了使组织结构更清晰，这里的blog集合（这个集合甚至不需要存在）跟它的两个子集合没有任何关系。</span><br><span class="line">在MongoDB中，使用子集合来组织数据非常高效，值得推荐</span><br><span class="line"></span><br><span class="line"><span class="comment">#3、当第一个文档插入时，集合就会被创建。合法的集合名：</span></span><br><span class="line">集合名不能是空字符串<span class="string">""</span>。</span><br><span class="line">集合名不能含有\<span class="number">0</span>字符（空字符)，这个字符表示集合名的结尾。</span><br><span class="line">集合名不能以<span class="string">"system."</span>开头，这是为系统集合保留的前缀。</span><br><span class="line">用户创建的集合名字不能含有保留字符。有些驱动程序的确支持在集合名里面包含，这是因为某些系统生成的集合中包含该字符。除非你要访问这种系统创建的集合，否则千万不要在名字里出现$。</span><br></pre></td></tr></table></figure>

<h3 id="2-3-数据库：在MongoDB中，多个文档组成集合，多个集合可以组成数据库"><a href="#2-3-数据库：在MongoDB中，多个文档组成集合，多个集合可以组成数据库" class="headerlink" title="2.3 数据库：在MongoDB中，多个文档组成集合，多个集合可以组成数据库"></a>2.3 数据库：在MongoDB中，多个文档组成集合，多个集合可以组成数据库</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">数据库也通过名字来标识。数据库名可以是满足以下条件的任意UTF<span class="number">-8</span>字符串：</span><br><span class="line"><span class="comment">#1、不能是空字符串（"")。</span></span><br><span class="line"><span class="comment">#2、不得含有' '（空格)、.、$、/、\和\0 (空字符)。</span></span><br><span class="line"><span class="comment">#3、应全部小写。</span></span><br><span class="line"><span class="comment">#4、最多64字节。</span></span><br><span class="line"></span><br><span class="line">有一些数据库名是保留的，可以直接访问这些有特殊作用的数据库。</span><br><span class="line"><span class="comment">#1、admin： 从身份认证的角度讲，这是“root”数据库，如果将一个用户添加到admin数据库，这个用户将自动获得所有数据库的权限。再者，一些特定的服务器端命令也只能从admin数据库运行，如列出所有数据库或关闭服务器</span></span><br><span class="line"><span class="comment">#2、local: 这个数据库永远都不可以复制，且一台服务器上的所有本地集合都可以存储在这个数据库中</span></span><br><span class="line"><span class="comment">#3、config: MongoDB用于分片设置时，分片信息会存储在config数据库中</span></span><br></pre></td></tr></table></figure>

<h3 id="2-4-强调：把数据库名添加到集合名前，得到集合的完全限定名，即命名空间"><a href="#2-4-强调：把数据库名添加到集合名前，得到集合的完全限定名，即命名空间" class="headerlink" title="2.4 强调：把数据库名添加到集合名前，得到集合的完全限定名，即命名空间"></a>2.4 强调：把数据库名添加到集合名前，得到集合的完全限定名，即命名空间</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">例如：</span><br><span class="line">如果要使用cms数据库中的blog.posts集合，这个集合的命名空间就是</span><br><span class="line">cmd.blog.posts。命名空间的长度不得超过<span class="number">121</span>个字节，且在实际使用中应该小于<span class="number">100</span>个字节</span><br></pre></td></tr></table></figure>

<p><img src="https://tva1.sinaimg.cn/large/00831rSTly1gdelxpstvnj311m0bqn2p.jpg" alt="image-20200401215347803"></p>
<h2 id="三-安装-amp-配置"><a href="#三-安装-amp-配置" class="headerlink" title="三 安装&amp;配置"></a>三 安装&amp;配置</h2><h3 id="3-1-安装"><a href="#3-1-安装" class="headerlink" title="3.1 安装"></a>3.1 安装</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#0、下载地址 https://www.mongodb.com/download-center/community，选择平台下载</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#1、安装，一路下一步</span></span><br><span class="line"><span class="comment">#2、会自动创建文件db和mongod.log文件,自动创建服务</span></span><br><span class="line"><span class="comment">#3、注意bin路径下的配置文件mongod.cfg</span></span><br><span class="line">storage:</span><br><span class="line">  dbPath: C:\Program Files\MongoDB\Server\<span class="number">4.2</span>\data</span><br><span class="line">  journal:</span><br><span class="line">    enabled: true</span><br><span class="line"><span class="comment"># where to write logging data.</span></span><br><span class="line">systemLog:</span><br><span class="line">  destination: file</span><br><span class="line">  logAppend: true</span><br><span class="line">  path:  C:\Program Files\MongoDB\Server\<span class="number">4.2</span>\log\mongod.log</span><br><span class="line"><span class="comment"># network interfaces</span></span><br><span class="line">net:</span><br><span class="line">  port: <span class="number">27017</span></span><br><span class="line">  bindIp: <span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#4、启动\关闭</span></span><br><span class="line">net start MongoDB</span><br><span class="line">net stop MongoDB</span><br><span class="line">mongod --config <span class="string">"mongod.cfg"</span></span><br><span class="line"><span class="comment"># mongod --config "mongod.cfg" --auth 开启认证</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#6、登录</span></span><br><span class="line">mongo</span><br><span class="line"><span class="comment"># 远程连接：./mongo --host 10.0.0.5 --port 27017</span></span><br><span class="line"><span class="comment">#7、安装robo3t（客户端，等同于Navicat）</span></span><br><span class="line">一路下一步</span><br></pre></td></tr></table></figure>

<h3 id="3-2-账号管理"><a href="#3-2-账号管理" class="headerlink" title="3.2 账号管理"></a>3.2 账号管理</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#注意，要管理哪个库，就在哪个库下建账号,管理员账号要建在amdin库下</span></span><br><span class="line"><span class="comment">#1、创建账号</span></span><br><span class="line">use admin</span><br><span class="line"><span class="comment">#全局变量 db ，当前在什么库下，这个db就是谁</span></span><br><span class="line">db.createUser(</span><br><span class="line">  &#123;</span><br><span class="line">    user: <span class="string">"root"</span>,</span><br><span class="line">    pwd: <span class="string">"123"</span>,</span><br><span class="line">    roles: [ &#123; role: <span class="string">"root"</span>, db: <span class="string">"admin"</span> &#125; ]</span><br><span class="line">  &#125;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">use test <span class="comment"># 空数据库不显示</span></span><br><span class="line">db.createUser(</span><br><span class="line">  &#123;</span><br><span class="line">    user: <span class="string">"lqz"</span>,</span><br><span class="line">    pwd: <span class="string">"123"</span>,</span><br><span class="line">    roles: [ &#123; role: <span class="string">"readWrite"</span>, db: <span class="string">"test"</span> &#125;,</span><br><span class="line">             &#123; role: <span class="string">"read"</span>, db: <span class="string">"db1"</span> &#125; ]</span><br><span class="line">  &#125;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="comment">#2、重启数据库</span></span><br><span class="line">net stop MongoDB</span><br><span class="line">net start MongoDB</span><br><span class="line"><span class="comment">#需要以开启认证的方式启动mongodb服务</span></span><br><span class="line">mongod --config <span class="string">"mongod.cfg"</span> --auth</span><br><span class="line"></span><br><span class="line"><span class="comment">#3、登录：注意使用双引号而非单引号</span></span><br><span class="line"><span class="comment">#以管理员登陆</span></span><br><span class="line">./mongo --host <span class="number">10.0</span><span class="number">.0</span><span class="number">.5</span> --port <span class="number">27017</span> -u <span class="string">"root"</span> -p <span class="string">"123"</span> --authenticationDatabase <span class="string">"admin"</span></span><br><span class="line"><span class="comment"># 以用户lqz登陆(只对test库有权限)</span></span><br><span class="line">./mongo --host <span class="number">10.0</span><span class="number">.0</span><span class="number">.5</span> --port <span class="number">27017</span> -u <span class="string">"lqz"</span> -p <span class="string">"123"</span> --authenticationDatabase <span class="string">"test"</span></span><br><span class="line">mongo --port <span class="number">27017</span> -u <span class="string">"root"</span> -p <span class="string">"123"</span> --authenticationDatabase <span class="string">"admin"</span></span><br><span class="line"></span><br><span class="line">也可以在登录之后用db.auth(<span class="string">"账号"</span>,<span class="string">"密码"</span>)登录</span><br><span class="line">mongo</span><br><span class="line">show dbs</span><br><span class="line">use admin</span><br><span class="line"><span class="comment"># db是一个全局变量，代表当前所有库</span></span><br><span class="line">db.auth(<span class="string">"root"</span>,<span class="string">"123"</span>)</span><br><span class="line">show tables；</span><br></pre></td></tr></table></figure>

<h2 id="四-基本数据类型"><a href="#四-基本数据类型" class="headerlink" title="四 基本数据类型"></a>四 基本数据类型</h2><p>1、在概念上，MongoDB的文档与Javascript的对象相近，因而可以认为它类似于JSON。JSON（<a href="http://www.json.org）是一种简单的数据表示方式：其规范仅用一段文字就能描述清楚（其官网证明了这点），且仅包含六种数据类型。">http://www.json.org）是一种简单的数据表示方式：其规范仅用一段文字就能描述清楚（其官网证明了这点），且仅包含六种数据类型。</a></p>
<p>2、这样有很多好处：易于理解、易于解析、易于记忆。然而从另一方面说，因为只有null、布尔、数字、字符串、数字和对象这几种数据类型，所以JSON的表达能力有一定的局限。</p>
<p>3、虽然JSON具备的这些类型已经具有很强的表现力，但绝大数应用（尤其是在于数据库打交道时）都还需要其他一些重要的类型。例如，JSON没有日期类型，这使得原本容易日期处理变得烦人。另外，JSON只有一种数字类型，无法区分浮点数和整数，更别区分32位和64位了。再者JSON无法表示其他一些通用类型，如正则表达式或函数。</p>
<p>4、MongoDB在保留了JSON基本键/值对特性的基础上，添加了其他一些数据类型。在不同的编程语言下，这些类型的确切表示有些许差异。下面说明了MongoDB支持的其他通用类型，以及如何正在文档中使用它们</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#1、null：用于表示空或不存在的字段</span></span><br><span class="line">d=&#123;<span class="string">'x'</span>:null&#125;</span><br><span class="line"><span class="comment">#2、布尔型：true和false</span></span><br><span class="line">d=&#123;<span class="string">'x'</span>:true,<span class="string">'y'</span>:false&#125;</span><br><span class="line"><span class="comment">#3、数值</span></span><br><span class="line">d=&#123;<span class="string">'x'</span>:<span class="number">3</span>,<span class="string">'y'</span>:<span class="number">3.1415926</span>&#125;</span><br><span class="line"><span class="comment">#4、字符串</span></span><br><span class="line">d=&#123;<span class="string">'x'</span>:<span class="string">'egon'</span>&#125;</span><br><span class="line"><span class="comment">#5、日期</span></span><br><span class="line">d=&#123;<span class="string">'x'</span>:new Date()&#125;</span><br><span class="line">d.x.getHours()</span><br><span class="line"><span class="comment">#6、正则表达式</span></span><br><span class="line">d=&#123;'pattern':/^egon.*?nb$/i&#125;</span><br><span class="line"></span><br><span class="line">正则写在／／内，后面的i代表:</span><br><span class="line">i 忽略大小写</span><br><span class="line">m 多行匹配模式</span><br><span class="line">x 忽略非转义的空白字符</span><br><span class="line">s 单行匹配模式</span><br><span class="line"></span><br><span class="line"><span class="comment">#7、数组</span></span><br><span class="line">d=&#123;<span class="string">'x'</span>:[<span class="number">1</span>,<span class="string">'a'</span>,<span class="string">'v'</span>]&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">#8、内嵌文档</span></span><br><span class="line">user=&#123;<span class="string">'name'</span>:<span class="string">'egon'</span>,<span class="string">'addr'</span>:&#123;<span class="string">'country'</span>:<span class="string">'China'</span>,<span class="string">'city'</span>:<span class="string">'YT'</span>&#125;&#125;</span><br><span class="line">user.addr.country</span><br><span class="line"></span><br><span class="line"><span class="comment">#9、对象id:是一个12字节的ID,是文档的唯一标识，不可变</span></span><br><span class="line">d=&#123;<span class="string">'x'</span>:ObjectId()&#125;</span><br></pre></td></tr></table></figure>

<p>_id和Objectid</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">MongoDB中存储的文档必须有一个<span class="string">"_id"</span>键。这个键的值可以是任意类型，默认是个ObjectId对象。</span><br><span class="line">在一个集合里，每个文档都有唯一的“_id”,确保集合里每个文档都能被唯一标识。</span><br><span class="line">不同集合<span class="string">"_id"</span>的值可以重复，但同一集合内<span class="string">"_id"</span>的值必须唯一</span><br><span class="line"></span><br><span class="line"><span class="comment">#1、ObjectId</span></span><br><span class="line">ObjectId是<span class="string">"_id"</span>的默认类型。因为设计MongoDb的初衷就是用作分布式数据库，所以能够在分片环境中生成</span><br><span class="line">唯一的标识符非常重要，而常规的做法：在多个服务器上同步自动增加主键既费时又费力，这就是MongoDB采用</span><br><span class="line">ObjectId的原因。</span><br><span class="line">ObjectId采用<span class="number">12</span>字节的存储空间，是一个由<span class="number">24</span>个十六进制数字组成的字符串</span><br><span class="line">    <span class="number">0</span>|<span class="number">1</span>|<span class="number">2</span>|<span class="number">3</span>|   <span class="number">4</span>|<span class="number">5</span>|<span class="number">6</span>|     <span class="number">7</span>|<span class="number">8</span>    <span class="number">9</span>|<span class="number">10</span>|<span class="number">11</span>    </span><br><span class="line">    时间戳      机器      PID    计数器</span><br><span class="line">如果快速创建多个ObjectId，会发现每次只有最后几位有变化。另外，中间的几位数字也会变化（要是在创建过程中停顿几秒）。</span><br><span class="line">这是ObjectId的创建方式导致的，如上图</span><br><span class="line"></span><br><span class="line">时间戳单位为秒，与随后<span class="number">5</span>个字节组合起来，提供了秒级的唯一性。这个<span class="number">4</span>个字节隐藏了文档的创建时间，绝大多数驱动程序都会提供</span><br><span class="line">一个方法，用于从ObjectId中获取这些信息。</span><br><span class="line"></span><br><span class="line">因为使用的是当前时间，很多用户担心要对服务器进行时钟同步。其实没必要，因为时间戳的实际值并不重要，只要它总是不停增加就好。</span><br><span class="line">接下来<span class="number">3</span>个字节是所在主机的唯一标识符。通常是机器主机名的散列值。这样就可以保证不同主机生成不同的ObjectId，不产生冲突</span><br><span class="line"></span><br><span class="line">接下来连个字节确保了在同一台机器上并发的多个进程产生的ObjectId是唯一的</span><br><span class="line"></span><br><span class="line">前<span class="number">9</span>个字节确保了同一秒钟不同机器不同进程产生的ObjectId是唯一的。最后<span class="number">3</span>个字节是一个自动增加的 计数器。确保相同进程的同一秒产生的</span><br><span class="line">ObjectId也是不一样的。</span><br><span class="line"></span><br><span class="line"><span class="comment">#2、自动生成_id</span></span><br><span class="line">如果插入文档时没有<span class="string">"_id"</span>键，系统会自帮你创建 一个。可以由MongoDb服务器来做这件事。</span><br><span class="line">但通常会在客户端由驱动程序完成。这一做法非常好地体现了MongoDb的哲学：能交给客户端驱动程序来做的事情就不要交给服务器来做。</span><br><span class="line">这种理念背后的原因是：即便是像MongoDB这样扩展性非常好的数据库，扩展应用层也要比扩展数据库层容易的多。将工作交给客户端做就</span><br><span class="line">减轻了数据库扩展的负担。</span><br></pre></td></tr></table></figure>



<h2 id="五-CURD操作"><a href="#五-CURD操作" class="headerlink" title="五 CURD操作"></a>五 CURD操作</h2><h3 id="5-1-数据库操作"><a href="#5-1-数据库操作" class="headerlink" title="5.1 数据库操作"></a>5.1 数据库操作</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#1、增</span></span><br><span class="line">use config <span class="comment">#如果数据库不存在，则创建数据库，否则切换到指定数据库。</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#2、查</span></span><br><span class="line">show dbs <span class="comment">#查看所有</span></span><br><span class="line">可以看到，我们刚创建的数据库config并不在数据库的列表中， 要显示它，我们需要向config数据库插入一些数据。</span><br><span class="line">db.table1.insert(&#123;<span class="string">'a'</span>:<span class="number">1</span>&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#3、删</span></span><br><span class="line">use config <span class="comment">#先切换到要删的库下</span></span><br><span class="line">db.dropDatabase() <span class="comment">#删除当前库</span></span><br></pre></td></tr></table></figure>

<h3 id="5-2-集合操作（表）"><a href="#5-2-集合操作（表）" class="headerlink" title="5.2 集合操作（表）"></a>5.2 集合操作（表）</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#1、增</span></span><br><span class="line">当第一个文档插入时，集合就会被创建</span><br><span class="line">&gt; use database1</span><br><span class="line">switched to db database1</span><br><span class="line">&gt; db.table1.insert(&#123;<span class="string">'a'</span>:<span class="number">1</span>&#125;)</span><br><span class="line">WriteResult(&#123; <span class="string">"nInserted"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; db.table2.insert(&#123;<span class="string">'b'</span>:<span class="number">2</span>&#125;)</span><br><span class="line">WriteResult(&#123; <span class="string">"nInserted"</span> : <span class="number">1</span> &#125;)</span><br><span class="line"><span class="comment">#注意 db.user和db.user.info是两个表</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#2、查</span></span><br><span class="line">&gt; show collections</span><br><span class="line">&gt; show tables</span><br><span class="line">table1</span><br><span class="line">table2</span><br><span class="line"></span><br><span class="line"><span class="comment">#3、删</span></span><br><span class="line">&gt; db.table1.drop()</span><br><span class="line">true</span><br><span class="line">&gt; show tables</span><br><span class="line">table2</span><br></pre></td></tr></table></figure>

<h3 id="5-3-文档操作"><a href="#5-3-文档操作" class="headerlink" title="5.3 文档操作"></a>5.3 文档操作</h3><h4 id="5-3-1-新增文档"><a href="#5-3-1-新增文档" class="headerlink" title="5.3.1 新增文档"></a>5.3.1 新增文档</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#单条插入与多条插入</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#1、没有指定_id则默认ObjectId,_id不能重复，且在插入后不可变</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#2、插入单条</span></span><br><span class="line">user0=&#123;</span><br><span class="line">    <span class="string">"name"</span>:<span class="string">"lqz"</span>,</span><br><span class="line">    <span class="string">"age"</span>:<span class="number">10</span>,</span><br><span class="line">    <span class="string">'hobbies'</span>:[<span class="string">'music'</span>,<span class="string">'read'</span>,<span class="string">'dancing'</span>],</span><br><span class="line">    <span class="string">'addr'</span>:&#123;</span><br><span class="line">        <span class="string">'country'</span>:<span class="string">'China'</span>,</span><br><span class="line">        <span class="string">'city'</span>:<span class="string">'BJ'</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">db.test.insert(user0)</span><br><span class="line">db.test.find()</span><br><span class="line"></span><br><span class="line"><span class="comment">#3、插入多条</span></span><br><span class="line">user1=&#123;</span><br><span class="line">    <span class="string">"_id"</span>:<span class="number">1</span>,</span><br><span class="line">    <span class="string">"name"</span>:<span class="string">"lqz1"</span>,</span><br><span class="line">    <span class="string">"age"</span>:<span class="number">10</span>,</span><br><span class="line">    <span class="string">'hobbies'</span>:[<span class="string">'music'</span>,<span class="string">'read'</span>,<span class="string">'dancing'</span>],</span><br><span class="line">    <span class="string">'addr'</span>:&#123;</span><br><span class="line">        <span class="string">'country'</span>:<span class="string">'China'</span>,</span><br><span class="line">        <span class="string">'city'</span>:<span class="string">'weifang'</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">user2=&#123;</span><br><span class="line">    <span class="string">"_id"</span>:<span class="number">2</span>,</span><br><span class="line">    <span class="string">"name"</span>:<span class="string">"lqz2"</span>,</span><br><span class="line">    <span class="string">"age"</span>:<span class="number">20</span>,</span><br><span class="line">    <span class="string">'hobbies'</span>:[<span class="string">'music'</span>,<span class="string">'read'</span>,<span class="string">'run'</span>],</span><br><span class="line">    <span class="string">'addr'</span>:&#123;</span><br><span class="line">        <span class="string">'country'</span>:<span class="string">'China'</span>,</span><br><span class="line">        <span class="string">'city'</span>:<span class="string">'hebei'</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">user3=&#123;</span><br><span class="line">    <span class="string">"_id"</span>:<span class="number">3</span>,</span><br><span class="line">    <span class="string">"name"</span>:<span class="string">"lqz3"</span>,</span><br><span class="line">    <span class="string">"age"</span>:<span class="number">30</span>,</span><br><span class="line">    <span class="string">'hobbies'</span>:[<span class="string">'music'</span>,<span class="string">'drink'</span>],</span><br><span class="line">    <span class="string">'addr'</span>:&#123;</span><br><span class="line">        <span class="string">'country'</span>:<span class="string">'China'</span>,</span><br><span class="line">        <span class="string">'city'</span>:<span class="string">'heibei'</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">user4=&#123;</span><br><span class="line">    <span class="string">"_id"</span>:<span class="number">4</span>,</span><br><span class="line">    <span class="string">"name"</span>:<span class="string">"lqz4"</span>,</span><br><span class="line">    <span class="string">"age"</span>:<span class="number">40</span>,</span><br><span class="line">    <span class="string">'hobbies'</span>:[<span class="string">'music'</span>,<span class="string">'read'</span>,<span class="string">'dancing'</span>,<span class="string">'tea'</span>],</span><br><span class="line">    <span class="string">'addr'</span>:&#123;</span><br><span class="line">        <span class="string">'country'</span>:<span class="string">'China'</span>,</span><br><span class="line">        <span class="string">'city'</span>:<span class="string">'BJ'</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">user5=&#123;</span><br><span class="line">    <span class="string">"_id"</span>:<span class="number">5</span>,</span><br><span class="line">    <span class="string">"name"</span>:<span class="string">"lqz5"</span>,</span><br><span class="line">    <span class="string">"age"</span>:<span class="number">50</span>,</span><br><span class="line">    <span class="string">'hobbies'</span>:[<span class="string">'music'</span>,<span class="string">'read'</span>,],</span><br><span class="line">    <span class="string">'addr'</span>:&#123;</span><br><span class="line">        <span class="string">'country'</span>:<span class="string">'China'</span>,</span><br><span class="line">        <span class="string">'city'</span>:<span class="string">'henan'</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">db.user.insertMany([user1,user2,user3,user4,user5])</span><br><span class="line"></span><br><span class="line"><span class="comment"># 有则覆盖，没则新增</span></span><br><span class="line">db.user.save(&#123;<span class="string">"_id"</span>:<span class="number">1</span>,<span class="string">"name"</span>:<span class="string">"lqz"</span>&#125;)</span><br><span class="line">db.user.save(&#123;<span class="string">"name"</span>:<span class="string">"lqz"</span>&#125;)</span><br></pre></td></tr></table></figure>

<h4 id="5-3-2-查询文档"><a href="#5-3-2-查询文档" class="headerlink" title="5.3.2 查询文档"></a>5.3.2 查询文档</h4><p>比较运算</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 比较运算</span></span><br><span class="line"><span class="comment"># SQL：=,!=,&gt;,&lt;,&gt;=,&lt;=</span></span><br><span class="line"><span class="comment"># MongoDB：&#123;key:value&#125;代表什么等于什么,"$ne","$gt","$lt","gte","lte",其中"$ne"能用于所有数据类型</span></span><br><span class="line">db.user.find().pretty()  <span class="comment"># 以json格式显示，了解</span></span><br><span class="line"><span class="comment">#1、select * from db1.user where name = "lqz1";</span></span><br><span class="line">db.user.find(&#123;<span class="string">'name'</span>:<span class="string">'lqz1'</span>&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#2、select * from db1.user where name != "lqz2";</span></span><br><span class="line">db.user.find(&#123;<span class="string">'name'</span>:&#123;<span class="string">"$ne"</span>:<span class="string">'lqz2'</span>&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#3、select * from db1.user where id &gt; 2;</span></span><br><span class="line">db.user.find(&#123;<span class="string">'_id'</span>:&#123;<span class="string">'$gt'</span>:<span class="number">2</span>&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#4、select * from db1.user where id &lt; 3;</span></span><br><span class="line">db.user.find(&#123;<span class="string">'_id'</span>:&#123;<span class="string">'$lt'</span>:<span class="number">3</span>&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#5、select * from db1.user where id &gt;= 2;</span></span><br><span class="line">db.user.find(&#123;<span class="string">"_id"</span>:&#123;<span class="string">"$gte"</span>:<span class="number">2</span>,&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#6、select * from db1.user where id &lt;= 2;</span></span><br><span class="line">db.user.find(&#123;<span class="string">"_id"</span>:&#123;<span class="string">"$lte"</span>:<span class="number">2</span>&#125;&#125;)</span><br></pre></td></tr></table></figure>

<p>逻辑运算</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#逻辑运算</span></span><br><span class="line"><span class="comment"># SQL：and，or，not ，mod（取余数）</span></span><br><span class="line"><span class="comment"># MongoDB：字典中逗号分隔的多个条件是and关系，"$or"的条件放到[]内,"$not"</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#1、select * from db1.user where id &gt;= 2 and id &lt; 4;</span></span><br><span class="line">db.user.find(&#123;<span class="string">'_id'</span>:&#123;<span class="string">"$gte"</span>:<span class="number">2</span>,<span class="string">"$lt"</span>:<span class="number">4</span>&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#2、select * from db1.user where id &gt;= 2 and age &lt; 40;</span></span><br><span class="line">db.user.find(&#123;<span class="string">"_id"</span>:&#123;<span class="string">"$gte"</span>:<span class="number">2</span>&#125;,<span class="string">"age"</span>:&#123;<span class="string">"$lt"</span>:<span class="number">40</span>&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#3、select * from db1.user where id &gt;= 5 or name = "lqz";</span></span><br><span class="line">db.user.find(&#123;</span><br><span class="line">    <span class="string">"$or"</span>:[</span><br><span class="line">        &#123;<span class="string">'_id'</span>:&#123;<span class="string">"$gte"</span>:<span class="number">5</span>&#125;&#125;,</span><br><span class="line">        &#123;<span class="string">"name"</span>:<span class="string">"lqz"</span>&#125;</span><br><span class="line">        ]</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">#4、select * from db1.user where id % 2=1;</span></span><br><span class="line">db.user.find(&#123;<span class="string">'_id'</span>:&#123;<span class="string">"$mod"</span>:[<span class="number">2</span>,<span class="number">1</span>]&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#5、上题，取反</span></span><br><span class="line">db.user.find(&#123;<span class="string">'_id'</span>:&#123;<span class="string">"$not"</span>:&#123;<span class="string">"$mod"</span>:[<span class="number">2</span>,<span class="number">1</span>]&#125;&#125;&#125;)</span><br></pre></td></tr></table></figure>

<p>成员运算</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 成员运算</span></span><br><span class="line"><span class="comment"># SQL：in，not in</span></span><br><span class="line"><span class="comment"># MongoDB："$in","$nin"</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#1、select * from db1.user where age in (20,30,31);</span></span><br><span class="line">db.user.find(&#123;<span class="string">"age"</span>:&#123;<span class="string">"$in"</span>:[<span class="number">20</span>,<span class="number">30</span>,<span class="number">31</span>]&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#2、select * from db1.user where name not in ('lqz1','lqz2');</span></span><br><span class="line">db.user.find(&#123;<span class="string">"name"</span>:&#123;<span class="string">"$nin"</span>:[<span class="string">'lqz1'</span>,<span class="string">'lqz2'</span>]&#125;&#125;)</span><br></pre></td></tr></table></figure>

<p>正则匹配</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># SQL: regexp 正则</span></span><br><span class="line"><span class="comment"># MongoDB: /正则表达/i</span></span><br><span class="line"><span class="comment">#1、select * from db1.user where name regexp '^l';</span></span><br><span class="line"><span class="comment"># 查询名字以l开头的人</span></span><br><span class="line">db.user.find(&#123;"name":/.*?/&#125;)</span><br><span class="line">db.user.find(&#123;<span class="string">"name"</span>:/^l/&#125;)</span><br><span class="line"><span class="comment"># 查询名字以l开头，以1结尾的所有数据</span></span><br><span class="line">db.user.find(&#123;"name":/^l.*?1$/&#125;)</span><br></pre></td></tr></table></figure>

<p>取指定字段</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#1、select name,age from db1.user where id=3;</span></span><br><span class="line">db.user.find(&#123;<span class="string">'_id'</span>:<span class="number">3</span>&#125;,&#123;<span class="string">'_id'</span>:<span class="number">0</span>,<span class="string">'name'</span>:<span class="number">1</span>,<span class="string">'age'</span>:<span class="number">1</span>&#125;)</span><br><span class="line"><span class="comment"># 0表示不显示，1表示显示</span></span><br></pre></td></tr></table></figure>

<p>查询数组</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#1、查看有dancing爱好的人</span></span><br><span class="line">db.user.find(&#123;<span class="string">'hobbies'</span>:<span class="string">'dancing'</span>&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#2、查看既有dancing爱好又有tea爱好的人</span></span><br><span class="line">db.user.find(&#123;</span><br><span class="line">    <span class="string">'hobbies'</span>:&#123;</span><br><span class="line">        <span class="string">"$all"</span>:[<span class="string">'dancing'</span>,<span class="string">'tea'</span>]</span><br><span class="line">        &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#3、查看第4个爱好为tea的人</span></span><br><span class="line">db.user.find(&#123;<span class="string">"hobbies.3"</span>:<span class="string">'tea'</span>&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#4、查看所有人最后两个爱好(注意没有hobbies字段的也会被查出)（本质用的是取指定字段，所以要放在后面的字典中）</span></span><br><span class="line">db.user.find(&#123;&#125;,&#123;<span class="string">'hobbies'</span>:&#123;<span class="string">"$slice"</span>:<span class="number">-2</span>&#125;,<span class="string">"age"</span>:<span class="number">0</span>,<span class="string">"_id"</span>:<span class="number">0</span>,<span class="string">"name"</span>:<span class="number">0</span>,<span class="string">"addr"</span>:<span class="number">0</span>&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#5、查看所有人的第2个到第3个爱好</span></span><br><span class="line">db.user.find(&#123;&#125;,&#123;<span class="string">'hobbies'</span>:&#123;<span class="string">"$slice"</span>:[<span class="number">1</span>,<span class="number">2</span>]&#125;,<span class="string">"age"</span>:<span class="number">0</span>,<span class="string">"_id"</span>:<span class="number">0</span>,<span class="string">"name"</span>:<span class="number">0</span>,<span class="string">"addr"</span>:<span class="number">0</span>&#125;)</span><br><span class="line"></span><br><span class="line">&gt; db.blog.find().pretty()</span><br><span class="line">&#123;</span><br><span class="line">        <span class="string">"_id"</span> : <span class="number">1</span>,</span><br><span class="line">        <span class="string">"name"</span> : <span class="string">"alex意外死亡的真相"</span>,</span><br><span class="line">        <span class="string">"comments"</span> : [</span><br><span class="line">                &#123;</span><br><span class="line">                        <span class="string">"name"</span> : <span class="string">"egon"</span>,</span><br><span class="line">                        <span class="string">"content"</span> : <span class="string">"alex是谁？？？"</span>,</span><br><span class="line">                        <span class="string">"thumb"</span> : <span class="number">200</span></span><br><span class="line">                &#125;,</span><br><span class="line">                &#123;</span><br><span class="line">                        <span class="string">"name"</span> : <span class="string">"wxx"</span>,</span><br><span class="line">                        <span class="string">"content"</span> : <span class="string">"我去，真的假的"</span>,</span><br><span class="line">                        <span class="string">"thumb"</span> : <span class="number">300</span></span><br><span class="line">                &#125;,</span><br><span class="line">                &#123;</span><br><span class="line">                        <span class="string">"name"</span> : <span class="string">"yxx"</span>,</span><br><span class="line">                        <span class="string">"content"</span> : <span class="string">"吃喝嫖赌抽，欠下两个亿"</span>,</span><br><span class="line">                        <span class="string">"thumb"</span> : <span class="number">40</span></span><br><span class="line">                &#125;,</span><br><span class="line">                &#123;</span><br><span class="line">                        <span class="string">"name"</span> : <span class="string">"egon"</span>,</span><br><span class="line">                        <span class="string">"content"</span> : <span class="string">"xxx"</span>,</span><br><span class="line">                        <span class="string">"thumb"</span> : <span class="number">0</span></span><br><span class="line">                &#125;</span><br><span class="line">        ]</span><br><span class="line">&#125;</span><br><span class="line">db.blog.find(&#123;&#125;,&#123;<span class="string">'comments'</span>:&#123;<span class="string">"$slice"</span>:<span class="number">-2</span>&#125;&#125;).pretty() <span class="comment">#查询最后两个</span></span><br><span class="line">db.blog.find(&#123;&#125;,&#123;<span class="string">'comments'</span>:&#123;<span class="string">"$slice"</span>:[<span class="number">1</span>,<span class="number">2</span>]&#125;&#125;).pretty() <span class="comment">#查询1到2</span></span><br></pre></td></tr></table></figure>

<p>排序</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 排序:--1代表升序，-1代表降序</span></span><br><span class="line">db.user.find().sort(&#123;<span class="string">"name"</span>:<span class="number">1</span>,&#125;)</span><br><span class="line">db.user.find().sort(&#123;<span class="string">"age"</span>:<span class="number">-1</span>,<span class="string">'_id'</span>:<span class="number">1</span>&#125;)</span><br></pre></td></tr></table></figure>

<p>分页</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 分页:--limit代表取多少个document，skip代表跳过前多少个document。 </span></span><br><span class="line"><span class="comment"># limit中表示一页显示的条数，skip(页码数*一页显示的条数)</span></span><br><span class="line">db.user.find().sort(&#123;<span class="string">'age'</span>:<span class="number">1</span>&#125;).limit(<span class="number">1</span>).skip(<span class="number">2</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 表关联</span></span><br><span class="line">user &#123;_id:<span class="number">1</span>,name:lqz,age:<span class="number">18</span>&#125;   一个人写多篇文章</span><br><span class="line">article ----》子查询</span><br><span class="line">	&#123;<span class="string">'userid'</span>:<span class="number">1</span>,article:红楼梦&#125;</span><br><span class="line">  &#123;<span class="string">'userid'</span>:<span class="number">1</span>,article:西游记&#125;</span><br></pre></td></tr></table></figure>

<p>获取数量</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 获取数量</span></span><br><span class="line">db.user.count(&#123;<span class="string">'age'</span>:&#123;<span class="string">"$gt"</span>:<span class="number">30</span>&#125;&#125;) </span><br><span class="line">--或者</span><br><span class="line">db.user.find(&#123;<span class="string">'age'</span>:&#123;<span class="string">"$gt"</span>:<span class="number">30</span>&#125;&#125;).count()</span><br></pre></td></tr></table></figure>

<p>其他</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#1、&#123;'key':null&#125; 匹配key的值为null或者没有这个key</span></span><br><span class="line">db.t2.insert(&#123;<span class="string">'a'</span>:<span class="number">10</span>,<span class="string">'b'</span>:<span class="number">111</span>&#125;)</span><br><span class="line">db.t2.insert(&#123;<span class="string">'a'</span>:<span class="number">20</span>&#125;)</span><br><span class="line">db.t2.insert(&#123;<span class="string">'b'</span>:null&#125;)</span><br><span class="line"></span><br><span class="line">&gt; db.t2.find(&#123;<span class="string">"b"</span>:null&#125;)</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a5cc2a7c1b4645aad959e5a"</span>), <span class="string">"a"</span> : <span class="number">20</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a5cc2a8c1b4645aad959e5b"</span>), <span class="string">"b"</span> : null &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">#2、查找所有</span></span><br><span class="line">db.user.find() <span class="comment">#等同于db.user.find(&#123;&#125;)</span></span><br><span class="line">db.user.find().pretty()</span><br><span class="line"></span><br><span class="line"><span class="comment">#3、查找一个，与find用法一致，只是只取匹配成功的第一个</span></span><br><span class="line">db.user.findOne(&#123;<span class="string">"_id"</span>:&#123;<span class="string">"$gt"</span>:<span class="number">3</span>&#125;&#125;)</span><br></pre></td></tr></table></figure>

<h4 id="5-3-3-修改文档"><a href="#5-3-3-修改文档" class="headerlink" title="5.3.3 修改文档"></a>5.3.3 修改文档</h4><p>语法介绍</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">update() 方法用于更新已存在的文档。语法格式如下：</span><br><span class="line">db.collection.update(</span><br><span class="line">   &lt;query&gt;,</span><br><span class="line">   &lt;update&gt;,</span><br><span class="line">   &#123;</span><br><span class="line">     upsert: &lt;boolean&gt;,</span><br><span class="line">     multi: &lt;boolean&gt;,</span><br><span class="line">     writeConcern: &lt;document&gt;</span><br><span class="line">   &#125;</span><br><span class="line">)</span><br><span class="line">参数说明：对比update db1.t1 set name=<span class="string">'EGON'</span>,sex=<span class="string">'Male'</span> where name=<span class="string">'egon'</span> <span class="keyword">and</span> age=<span class="number">18</span>;</span><br><span class="line"></span><br><span class="line">db.collection.update(</span><br><span class="line">   &#123;name:&#123;$ne:lqz&#125;&#125;,</span><br><span class="line">   &#123;字典&#125;,</span><br><span class="line">   &#123;</span><br><span class="line">     upsert: &lt;boolean&gt;,</span><br><span class="line">     multi: &lt;boolean&gt;,</span><br><span class="line">     writeConcern: &lt;document&gt;</span><br><span class="line">   &#125;</span><br><span class="line">)</span><br><span class="line">query : 相当于where条件。</span><br><span class="line">update : update的对象和一些更新的操作符（如$,$inc...等，相当于set后面的</span><br><span class="line">upsert : 可选，默认为false，代表如果不存在update的记录不更新也不插入，设置为true代表插入。</span><br><span class="line">multi : 可选，默认为false，代表只更新找到的第一条记录，设为true,代表更新找到的全部记录。</span><br><span class="line">writeConcern :可选，抛出异常的级别。</span><br><span class="line"></span><br><span class="line">更新操作是不可分割的：若两个更新同时发送，先到达服务器的先执行，然后执行另外一个，不会破坏文档。</span><br></pre></td></tr></table></figure>

<p>覆盖式</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#注意：除非是删除，否则_id是始终不会变的</span></span><br><span class="line"><span class="comment">#1、覆盖式:</span></span><br><span class="line">db.user.update(&#123;<span class="string">'age'</span>:<span class="number">30</span>&#125;,&#123;<span class="string">"name"</span>:<span class="string">"lqz9"</span>,<span class="string">"hobbies_count"</span>:<span class="number">3</span>&#125;)</span><br><span class="line">是用&#123;<span class="string">"_id"</span>:<span class="number">3</span>,<span class="string">"name"</span>:<span class="string">"lqz3"</span>,<span class="string">"hobbies_count"</span>:<span class="number">3</span>&#125;覆盖原来的记录</span><br><span class="line"></span><br><span class="line"><span class="comment">#2、一种最简单的更新就是用一个新的文档完全替换匹配的文档。这适用于大规模式迁移的情况。例如</span></span><br><span class="line">var obj=db.user.findOne(&#123;<span class="string">"_id"</span>:<span class="number">4</span>&#125;)</span><br><span class="line"></span><br><span class="line">obj.username=obj.name+<span class="string">'NB'</span></span><br><span class="line">obj.hobbies_count++</span><br><span class="line">delete obj.age</span><br><span class="line">delete obj._id</span><br><span class="line"></span><br><span class="line">db.user.update(&#123;<span class="string">"_id"</span>:<span class="number">2</span>&#125;,obj)</span><br></pre></td></tr></table></figure>

<p>设置$set</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#设置：$set</span></span><br><span class="line"></span><br><span class="line">通常文档只会有一部分需要更新。可以使用原子性的更新修改器，指定对文档中的某些字段进行更新。</span><br><span class="line">更新修改器是种特殊的键，用来指定复杂的更新操作，比如修改、增加后者删除</span><br><span class="line"></span><br><span class="line"><span class="comment">#1、update db1.user set  name="张三" where id = 2</span></span><br><span class="line">db.user.update(&#123;<span class="string">'_id'</span>:<span class="number">2</span>&#125;,&#123;<span class="string">"$set"</span>:&#123;<span class="string">"name"</span>:<span class="string">"张三"</span>,&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#2、没有匹配成功则新增一条&#123;"upsert":true&#125;</span></span><br><span class="line">db.user.update(&#123;<span class="string">'_id'</span>:<span class="number">6</span>&#125;,&#123;<span class="string">"$set"</span>:&#123;<span class="string">"name"</span>:<span class="string">"李飞刀"</span>,<span class="string">"age"</span>:<span class="number">18</span>&#125;&#125;,&#123;<span class="string">"upsert"</span>:true&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#3、默认只改匹配成功的第一条,&#123;"multi":改多条&#125;</span></span><br><span class="line">db.user.update(&#123;<span class="string">'_id'</span>:&#123;<span class="string">"$gt"</span>:<span class="number">4</span>&#125;&#125;,&#123;<span class="string">"$set"</span>:&#123;<span class="string">"age"</span>:<span class="number">28</span>&#125;&#125;)</span><br><span class="line">db.user.update(&#123;<span class="string">'_id'</span>:&#123;<span class="string">"$gte"</span>:<span class="number">4</span>&#125;&#125;,&#123;<span class="string">"$set"</span>:&#123;<span class="string">"age"</span>:<span class="number">38</span>&#125;&#125;,&#123;<span class="string">"multi"</span>:true&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#4、修改内嵌文档，把名字为lqz4的人所在的地址国家改成Japan</span></span><br><span class="line">db.user.update(&#123;<span class="string">'name'</span>:<span class="string">"lqz4"</span>&#125;,&#123;<span class="string">"$set"</span>:&#123;<span class="string">"addr.country"</span>:<span class="string">"Japan"</span>&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#5、把名字为lqz4的人的第2个爱好改成sleep</span></span><br><span class="line">db.user.update(&#123;<span class="string">'name'</span>:<span class="string">"lqz4"</span>&#125;,&#123;<span class="string">"$set"</span>:&#123;<span class="string">"hobbies.1"</span>:<span class="string">"sleep"</span>&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#6、删除lqz4的爱好,$unset</span></span><br><span class="line">db.user.update(&#123;<span class="string">'name'</span>:<span class="string">"lqz4"</span>&#125;,&#123;<span class="string">"$unset"</span>:&#123;<span class="string">"hobbies"</span>:<span class="string">""</span>&#125;&#125;)</span><br></pre></td></tr></table></figure>

<p>增加和减少</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#增加和减少：$inc</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#1、所有人年龄增加一岁</span></span><br><span class="line">db.user.update(&#123;&#125;,</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="string">"$inc"</span>:&#123;<span class="string">"age"</span>:<span class="number">1</span>&#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="string">"multi"</span>:true</span><br><span class="line">    &#125;</span><br><span class="line">    )</span><br><span class="line"><span class="comment">#2、所有人年龄减少5岁</span></span><br><span class="line">db.user.update(&#123;&#125;,</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="string">"$inc"</span>:&#123;<span class="string">"age"</span>:<span class="number">-5</span>&#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="string">"multi"</span>:true</span><br><span class="line">    &#125;</span><br><span class="line">    )</span><br></pre></td></tr></table></figure>

<p>添加删除组内元素 $push $pop $pull</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#添加删除数组内元素</span></span><br><span class="line">    </span><br><span class="line">往数组内添加元素:$push</span><br><span class="line"><span class="comment">#1、为名字为lqz的人添加一个爱好read</span></span><br><span class="line">db.user.update(&#123;<span class="string">"name"</span>:<span class="string">"lqz"</span>&#125;,&#123;<span class="string">"$push"</span>:&#123;<span class="string">"hobbies"</span>:<span class="string">"read"</span>&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#2、为名字为lqz的人一次添加多个爱好tea，dancing</span></span><br><span class="line">db.user.update(&#123;<span class="string">"name"</span>:<span class="string">"lqz"</span>&#125;,&#123;<span class="string">"$push"</span>:&#123;</span><br><span class="line">    <span class="string">"hobbies"</span>:&#123;<span class="string">"$each"</span>:[<span class="string">"tea"</span>,<span class="string">"dancing"</span>]&#125;</span><br><span class="line">&#125;&#125;)</span><br><span class="line"></span><br><span class="line">按照位置且只能从开头或结尾删除元素：$pop</span><br><span class="line"><span class="comment">#3、&#123;"$pop":&#123;"key":1&#125;&#125; 从数组末尾删除一个元素</span></span><br><span class="line"></span><br><span class="line">db.user.update(&#123;<span class="string">"name"</span>:<span class="string">"lqz"</span>&#125;,&#123;<span class="string">"$pop"</span>:&#123;</span><br><span class="line">    <span class="string">"hobbies"</span>:<span class="number">1</span>&#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#4、&#123;"$pop":&#123;"key":-1&#125;&#125; 从头部删除</span></span><br><span class="line">db.user.update(&#123;<span class="string">"name"</span>:<span class="string">"lqz"</span>&#125;,&#123;<span class="string">"$pop"</span>:&#123;</span><br><span class="line">    <span class="string">"hobbies"</span>:<span class="number">-1</span>&#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#5、按照条件删除元素,："$pull" 把符合条件的统统删掉，而$pop只能从两端删</span></span><br><span class="line"><span class="comment"># 删除所有国家为chine的人的read爱好</span></span><br><span class="line">db.user.update(&#123;<span class="string">'addr.country'</span>:<span class="string">"China"</span>&#125;,&#123;<span class="string">"$pull"</span>:&#123;</span><br><span class="line">    <span class="string">"hobbies"</span>:<span class="string">"read"</span>&#125;</span><br><span class="line">&#125;,</span><br><span class="line">&#123;</span><br><span class="line">    <span class="string">"multi"</span>:true</span><br><span class="line">&#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<p>避免重复 “$addToSet”</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#避免添加重复："$addToSet"</span></span><br><span class="line"></span><br><span class="line">db.urls.insert(&#123;<span class="string">"_id"</span>:<span class="number">1</span>,<span class="string">"urls"</span>:[]&#125;)</span><br><span class="line"></span><br><span class="line">db.urls.update(&#123;<span class="string">"_id"</span>:<span class="number">1</span>&#125;,&#123;<span class="string">"$addToSet"</span>:&#123;<span class="string">"urls"</span>:<span class="string">'http://www.baidu.com'</span>&#125;&#125;)</span><br><span class="line">db.urls.update(&#123;<span class="string">"_id"</span>:<span class="number">1</span>&#125;,&#123;<span class="string">"$addToSet"</span>:&#123;<span class="string">"urls"</span>:<span class="string">'http://www.baidu.com'</span>&#125;&#125;)</span><br><span class="line">db.urls.update(&#123;<span class="string">"_id"</span>:<span class="number">1</span>&#125;,&#123;<span class="string">"$addToSet"</span>:&#123;<span class="string">"urls"</span>:<span class="string">'http://www.baidu.com'</span>&#125;&#125;)</span><br><span class="line"></span><br><span class="line">db.urls.update(&#123;<span class="string">"_id"</span>:<span class="number">1</span>&#125;,&#123;</span><br><span class="line">    <span class="string">"$addToSet"</span>:&#123;</span><br><span class="line">        <span class="string">"urls"</span>:&#123;</span><br><span class="line">        <span class="string">"$each"</span>:[</span><br><span class="line">            <span class="string">'http://www.baidu.com'</span>,</span><br><span class="line">            <span class="string">'http://www.baidu.com'</span>,</span><br><span class="line">            <span class="string">'http://www.xxxx.com'</span></span><br><span class="line">            ]</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<p>其他</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#1、了解：限制大小"$slice"，只留最后n个</span></span><br><span class="line"></span><br><span class="line">db.user.update(&#123;<span class="string">"_id"</span>:<span class="number">5</span>&#125;,&#123;</span><br><span class="line">    <span class="string">"$push"</span>:&#123;<span class="string">"hobbies"</span>:&#123;</span><br><span class="line">        <span class="string">"$each"</span>:[<span class="string">"read"</span>,<span class="string">'music'</span>,<span class="string">'dancing'</span>],</span><br><span class="line">        <span class="string">"$slice"</span>:<span class="number">-2</span></span><br><span class="line">    &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#2、了解：排序The $sort element value must be either 1 or -1"</span></span><br><span class="line">db.user.update(&#123;<span class="string">"_id"</span>:<span class="number">5</span>&#125;,&#123;</span><br><span class="line">    <span class="string">"$push"</span>:&#123;<span class="string">"hobbies"</span>:&#123;</span><br><span class="line">        <span class="string">"$each"</span>:[<span class="string">"read"</span>,<span class="string">'music'</span>,<span class="string">'dancing'</span>],</span><br><span class="line">        <span class="string">"$slice"</span>:<span class="number">-1</span>,</span><br><span class="line">        <span class="string">"$sort"</span>:<span class="number">-1</span></span><br><span class="line">    &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#注意：不能只将"$slice"或者"$sort"与"$push"配合使用，且必须使用"$eah"</span></span><br></pre></td></tr></table></figure>



<h4 id="5-3-4-删除文档"><a href="#5-3-4-删除文档" class="headerlink" title="5.3.4 删除文档"></a>5.3.4 删除文档</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#1、删除多个中的第一个</span></span><br><span class="line">db.user.deleteOne(&#123; <span class="string">'age'</span>: <span class="number">8</span> &#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#2、删除国家为China的全部</span></span><br><span class="line">db.user.deleteMany( &#123;<span class="string">'addr.country'</span>: <span class="string">'China'</span>&#125; ) </span><br><span class="line"></span><br><span class="line"><span class="comment">#3、删除全部</span></span><br><span class="line">db.user.deleteMany(&#123;&#125;)</span><br></pre></td></tr></table></figure>

<h4 id="5-3-5-聚合"><a href="#5-3-5-聚合" class="headerlink" title="5.3.5 聚合"></a>5.3.5 聚合</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">如果你有数据存储在MongoDB中，你想做的可能就不仅仅是将数据提取出来那么简单了；你可能希望对数据进行分析并加以利用。MongoDB提供了以下聚合工具：</span><br><span class="line"><span class="comment">#1、聚合框架</span></span><br><span class="line"><span class="comment">#2、MapReduce(详见MongoDB权威指南)</span></span><br><span class="line"><span class="comment">#3、几个简单聚合命令：count、distinct和group。(详见MongoDB权威指南)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#聚合框架：</span></span><br><span class="line">可以使用多个构件创建一个管道，上一个构件的结果传给下一个构件。</span><br><span class="line">这些构件包括（括号内为构件对应的操作符）：筛选($match)、投射($project)、分组($group)、排序($sort)、限制($limit)、跳过($skip)</span><br><span class="line">不同的管道操作符可以任意组合，重复使用</span><br></pre></td></tr></table></figure>

<p>准备数据</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> pymongo <span class="keyword">import</span> MongoClient</span><br><span class="line"><span class="keyword">import</span> datetime</span><br><span class="line"></span><br><span class="line">client=MongoClient(<span class="string">'mongodb://root:123@localhost:27017'</span>)</span><br><span class="line">table=client[<span class="string">'db1'</span>][<span class="string">'emp'</span>]</span><br><span class="line"><span class="comment"># table.drop()</span></span><br><span class="line"></span><br><span class="line">l=[</span><br><span class="line">(<span class="string">'egon'</span>,<span class="string">'male'</span>,<span class="number">18</span>,<span class="string">'20170301'</span>,<span class="string">'老男孩驻沙河办事处外交大使'</span>,<span class="number">7300.33</span>,<span class="number">401</span>,<span class="number">1</span>), <span class="comment">#以下是教学部</span></span><br><span class="line">(<span class="string">'alex'</span>,<span class="string">'male'</span>,<span class="number">78</span>,<span class="string">'20150302'</span>,<span class="string">'teacher'</span>,<span class="number">1000000.31</span>,<span class="number">401</span>,<span class="number">1</span>),</span><br><span class="line">(<span class="string">'wupeiqi'</span>,<span class="string">'male'</span>,<span class="number">81</span>,<span class="string">'20130305'</span>,<span class="string">'teacher'</span>,<span class="number">8300</span>,<span class="number">401</span>,<span class="number">1</span>),</span><br><span class="line">(<span class="string">'yuanhao'</span>,<span class="string">'male'</span>,<span class="number">73</span>,<span class="string">'20140701'</span>,<span class="string">'teacher'</span>,<span class="number">3500</span>,<span class="number">401</span>,<span class="number">1</span>),</span><br><span class="line">(<span class="string">'liwenzhou'</span>,<span class="string">'male'</span>,<span class="number">28</span>,<span class="string">'20121101'</span>,<span class="string">'teacher'</span>,<span class="number">2100</span>,<span class="number">401</span>,<span class="number">1</span>),</span><br><span class="line">(<span class="string">'jingliyang'</span>,<span class="string">'female'</span>,<span class="number">18</span>,<span class="string">'20110211'</span>,<span class="string">'teacher'</span>,<span class="number">9000</span>,<span class="number">401</span>,<span class="number">1</span>),</span><br><span class="line">(<span class="string">'jinxin'</span>,<span class="string">'male'</span>,<span class="number">18</span>,<span class="string">'19000301'</span>,<span class="string">'teacher'</span>,<span class="number">30000</span>,<span class="number">401</span>,<span class="number">1</span>),</span><br><span class="line">(<span class="string">'成龙'</span>,<span class="string">'male'</span>,<span class="number">48</span>,<span class="string">'20101111'</span>,<span class="string">'teacher'</span>,<span class="number">10000</span>,<span class="number">401</span>,<span class="number">1</span>),</span><br><span class="line"></span><br><span class="line">(<span class="string">'歪歪'</span>,<span class="string">'female'</span>,<span class="number">48</span>,<span class="string">'20150311'</span>,<span class="string">'sale'</span>,<span class="number">3000.13</span>,<span class="number">402</span>,<span class="number">2</span>),<span class="comment">#以下是销售部门</span></span><br><span class="line">(<span class="string">'丫丫'</span>,<span class="string">'female'</span>,<span class="number">38</span>,<span class="string">'20101101'</span>,<span class="string">'sale'</span>,<span class="number">2000.35</span>,<span class="number">402</span>,<span class="number">2</span>),</span><br><span class="line">(<span class="string">'丁丁'</span>,<span class="string">'female'</span>,<span class="number">18</span>,<span class="string">'20110312'</span>,<span class="string">'sale'</span>,<span class="number">1000.37</span>,<span class="number">402</span>,<span class="number">2</span>),</span><br><span class="line">(<span class="string">'星星'</span>,<span class="string">'female'</span>,<span class="number">18</span>,<span class="string">'20160513'</span>,<span class="string">'sale'</span>,<span class="number">3000.29</span>,<span class="number">402</span>,<span class="number">2</span>),</span><br><span class="line">(<span class="string">'格格'</span>,<span class="string">'female'</span>,<span class="number">28</span>,<span class="string">'20170127'</span>,<span class="string">'sale'</span>,<span class="number">4000.33</span>,<span class="number">402</span>,<span class="number">2</span>),</span><br><span class="line"></span><br><span class="line">(<span class="string">'张野'</span>,<span class="string">'male'</span>,<span class="number">28</span>,<span class="string">'20160311'</span>,<span class="string">'operation'</span>,<span class="number">10000.13</span>,<span class="number">403</span>,<span class="number">3</span>), <span class="comment">#以下是运营部门</span></span><br><span class="line">(<span class="string">'程咬金'</span>,<span class="string">'male'</span>,<span class="number">18</span>,<span class="string">'19970312'</span>,<span class="string">'operation'</span>,<span class="number">20000</span>,<span class="number">403</span>,<span class="number">3</span>),</span><br><span class="line">(<span class="string">'程咬银'</span>,<span class="string">'female'</span>,<span class="number">18</span>,<span class="string">'20130311'</span>,<span class="string">'operation'</span>,<span class="number">19000</span>,<span class="number">403</span>,<span class="number">3</span>),</span><br><span class="line">(<span class="string">'程咬铜'</span>,<span class="string">'male'</span>,<span class="number">18</span>,<span class="string">'20150411'</span>,<span class="string">'operation'</span>,<span class="number">18000</span>,<span class="number">403</span>,<span class="number">3</span>),</span><br><span class="line">(<span class="string">'程咬铁'</span>,<span class="string">'female'</span>,<span class="number">18</span>,<span class="string">'20140512'</span>,<span class="string">'operation'</span>,<span class="number">17000</span>,<span class="number">403</span>,<span class="number">3</span>)</span><br><span class="line">]</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> n,item <span class="keyword">in</span> enumerate(l):</span><br><span class="line">    d=&#123;</span><br><span class="line">        <span class="string">"_id"</span>:n,</span><br><span class="line">        <span class="string">'name'</span>:item[<span class="number">0</span>],</span><br><span class="line">        <span class="string">'sex'</span>:item[<span class="number">1</span>],</span><br><span class="line">        <span class="string">'age'</span>:item[<span class="number">2</span>],</span><br><span class="line">        <span class="string">'hire_date'</span>:datetime.datetime.strptime(item[<span class="number">3</span>],<span class="string">'%Y%m%d'</span>),</span><br><span class="line">        <span class="string">'post'</span>:item[<span class="number">4</span>],</span><br><span class="line">        <span class="string">'salary'</span>:item[<span class="number">5</span>]</span><br><span class="line">    &#125;</span><br><span class="line">    table.save(d)</span><br></pre></td></tr></table></figure>

<p>筛选 “$match”</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">&#123;<span class="string">"$match"</span>:&#123;<span class="string">"字段"</span>:<span class="string">"条件"</span>&#125;&#125;,可以使用任何常用查询操作符$gt,$lt,$<span class="keyword">in</span>等</span><br><span class="line"></span><br><span class="line"><span class="comment">#例1、select * from db1.emp where post='teacher';</span></span><br><span class="line">db.emp.aggregate(&#123;<span class="string">"$match"</span>:&#123;<span class="string">"post"</span>:<span class="string">"teacher"</span>&#125;&#125;) <span class="comment"># shell版本不匹配，会出错</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#例2、select * from db1.emp where id &gt; 3 group by post;  </span></span><br><span class="line"><span class="comment"># 计算每个部门的平均工资</span></span><br><span class="line">select post <span class="keyword">as</span> _id,avg(salary) <span class="keyword">as</span> avg_salary <span class="keyword">from</span> db1.emp where id &gt; <span class="number">3</span> group by post;  </span><br><span class="line">db.emp.aggregate(</span><br><span class="line">    &#123;<span class="string">"$match"</span>:&#123;<span class="string">"_id"</span>:&#123;<span class="string">"$gt"</span>:<span class="number">3</span>&#125;&#125;&#125;,</span><br><span class="line">    &#123;<span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:<span class="string">"$post"</span>,<span class="string">'avg_salary'</span>:&#123;<span class="string">"$avg"</span>:<span class="string">"$salary"</span>&#125;&#125;&#125;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="comment">#例3、select post as _id,avg(salary) as avg_salary from db1.emp where id &gt; 3 group by post having avg(avg_salary) &gt; 10000; </span></span><br><span class="line"><span class="comment"># 查询平均工资大于10000的部门</span></span><br><span class="line">db.emp.aggregate(</span><br><span class="line">    &#123;<span class="string">"$match"</span>:&#123;<span class="string">"_id"</span>:&#123;<span class="string">"$gt"</span>:<span class="number">3</span>&#125;&#125;&#125;,</span><br><span class="line">    &#123;<span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:<span class="string">"$post"</span>,<span class="string">'avg_salary'</span>:&#123;<span class="string">"$avg"</span>:<span class="string">"$salary"</span>&#125;&#125;&#125;,</span><br><span class="line">    &#123;<span class="string">"$match"</span>:&#123;<span class="string">"avg_salary"</span>:&#123;<span class="string">"$gt"</span>:<span class="number">10000</span>&#125;&#125;&#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<p>投射 $project</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line">&#123;<span class="string">"$project"</span>:&#123;<span class="string">"要保留的字段名"</span>:<span class="number">1</span>,<span class="string">"要去掉的字段名"</span>:<span class="number">0</span>,<span class="string">"新增的字段名"</span>:<span class="string">"表达式"</span>&#125;&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">#1、select name,post,(age+1) as new_age from db1.emp;</span></span><br><span class="line">db.emp.aggregate(</span><br><span class="line">    &#123;<span class="string">"$project"</span>:&#123;</span><br><span class="line">        <span class="string">"name"</span>:<span class="number">1</span>,</span><br><span class="line">        <span class="string">"post"</span>:<span class="number">1</span>,</span><br><span class="line">        <span class="string">"new_age"</span>:&#123;<span class="string">"$add"</span>:[<span class="string">"$age"</span>,<span class="number">1</span>]&#125;</span><br><span class="line">        &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#2、表达式之数学表达式</span></span><br><span class="line">&#123;<span class="string">"$add"</span>:[expr1,expr2,...,exprN]&#125; <span class="comment">#相加</span></span><br><span class="line">&#123;<span class="string">"$subtract"</span>:[expr1,expr2]&#125; <span class="comment">#第一个减第二个</span></span><br><span class="line">&#123;<span class="string">"$multiply"</span>:[expr1,expr2,...,exprN]&#125; <span class="comment">#相乘</span></span><br><span class="line">&#123;<span class="string">"$divide"</span>:[expr1,expr2]&#125; <span class="comment">#第一个表达式除以第二个表达式的商作为结果</span></span><br><span class="line">&#123;<span class="string">"$mod"</span>:[expr1,expr2]&#125; <span class="comment">#第一个表达式除以第二个表达式得到的余数作为结果</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#3、表达式之日期表达式:$year,$month,$week,$dayOfMonth,$dayOfWeek,$dayOfYear,$hour,$minute,$second</span></span><br><span class="line"><span class="comment">#例如：select name,date_format("%Y") as hire_year from db1.emp</span></span><br><span class="line">db.emp.aggregate(</span><br><span class="line">    &#123;<span class="string">"$project"</span>:&#123;<span class="string">"name"</span>:<span class="number">1</span>,<span class="string">"hire_year"</span>:&#123;<span class="string">"$year"</span>:<span class="string">"$hire_date"</span>&#125;&#125;&#125;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="comment">#例如查看每个员工的工作多长时间</span></span><br><span class="line">db.emp.aggregate(</span><br><span class="line">    &#123;<span class="string">"$project"</span>:&#123;<span class="string">"name"</span>:<span class="number">1</span>,<span class="string">"hire_period"</span>:&#123;</span><br><span class="line">        <span class="string">"$subtract"</span>:[</span><br><span class="line">            &#123;<span class="string">"$year"</span>:new Date()&#125;,</span><br><span class="line">            &#123;<span class="string">"$year"</span>:<span class="string">"$hire_date"</span>&#125;</span><br><span class="line">        ]</span><br><span class="line">    &#125;&#125;&#125;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">#4、字符串表达式</span></span><br><span class="line">&#123;<span class="string">"$substr"</span>:[字符串/$值为字符串的字段名,起始位置,截取几个字节]&#125;</span><br><span class="line">&#123;<span class="string">"$concat"</span>:[expr1,expr2,...,exprN]&#125; <span class="comment">#指定的表达式或字符串连接在一起返回,只支持字符串拼接</span></span><br><span class="line">&#123;<span class="string">"$toLower"</span>:expr&#125;</span><br><span class="line">&#123;<span class="string">"$toUpper"</span>:expr&#125;</span><br><span class="line"></span><br><span class="line">db.emp.aggregate( &#123;<span class="string">"$project"</span>:&#123;<span class="string">"NAME"</span>:&#123;<span class="string">"$toUpper"</span>:<span class="string">"$name"</span>&#125;&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 除egon外，所有人名字加SB</span></span><br><span class="line"></span><br><span class="line">db.emp.aggregate(</span><br><span class="line">    &#123;<span class="string">"$match"</span>:&#123;<span class="string">"name"</span>:&#123;<span class="string">"$ne"</span>:<span class="string">"egon"</span>&#125;&#125;&#125;,</span><br><span class="line">    &#123;<span class="string">"$project"</span>:</span><br><span class="line">        &#123;<span class="string">"_id"</span>:<span class="number">0</span>,<span class="string">"new_name"</span>:</span><br><span class="line">            &#123;<span class="string">"$concat"</span>:</span><br><span class="line">                [<span class="string">"$name"</span>,<span class="string">"SB"</span>]</span><br><span class="line">                &#125;  </span><br><span class="line">            &#125;&#125;            </span><br><span class="line">)</span><br><span class="line"><span class="comment"># 取除egon外， 所有人名字3个字节（utf8编码，3个字节一个汉字）</span></span><br><span class="line">db.emp.aggregate(</span><br><span class="line">    &#123;<span class="string">"$match"</span>:&#123;<span class="string">"name"</span>:&#123;<span class="string">"$ne"</span>:<span class="string">"egon"</span>&#125;&#125;&#125;,</span><br><span class="line">    &#123;<span class="string">"$project"</span>:</span><br><span class="line">        &#123;<span class="string">"_id"</span>:<span class="number">0</span>,<span class="string">"new_name"</span>:</span><br><span class="line">            &#123;<span class="string">"$substr"</span>:</span><br><span class="line">                [<span class="string">"$name"</span>,<span class="number">0</span>,<span class="number">3</span>]</span><br><span class="line">                &#125;  </span><br><span class="line">            &#125;&#125;            </span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<p>分组 $group</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">&#123;<span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:分组字段,<span class="string">"新的字段名"</span>:聚合操作符&#125;&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">#1、将分组字段传给$group函数的_id字段即可</span></span><br><span class="line">&#123;<span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:<span class="string">"$sex"</span>&#125;&#125; <span class="comment">#按照性别分组</span></span><br><span class="line">&#123;<span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:<span class="string">"$post"</span>&#125;&#125; <span class="comment">#按照职位分组</span></span><br><span class="line">&#123;<span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:&#123;<span class="string">"state"</span>:<span class="string">"$state"</span>,<span class="string">"city"</span>:<span class="string">"$city"</span>&#125;&#125;&#125; <span class="comment">#按照多个字段分组，比如按照州市分组</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#2、分组后聚合得结果,类似于sql中聚合函数的聚合操作符：$sum、$avg、$max、$min、$first、$last</span></span><br><span class="line"><span class="comment">#例1：select post,max(salary) as max_salary from db1.emp group by post; </span></span><br><span class="line">db.emp.aggregate(&#123;<span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:<span class="string">"$post"</span>,<span class="string">"max_salary"</span>:&#123;<span class="string">"$max"</span>:<span class="string">"$salary"</span>&#125;&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#例2：去每个部门最大薪资与最低薪资</span></span><br><span class="line">db.emp.aggregate(&#123;<span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:<span class="string">"$post"</span>,<span class="string">"max_salary"</span>:&#123;<span class="string">"$max"</span>:<span class="string">"$salary"</span>&#125;,<span class="string">"min_salary"</span>:&#123;<span class="string">"$min"</span>:<span class="string">"$salary"</span>&#125;&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#例3：如果字段是排序后的，那么$first,$last会很有用,比用$max和$min效率高</span></span><br><span class="line">db.emp.aggregate(&#123;<span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:<span class="string">"$post"</span>,<span class="string">"first_id"</span>:&#123;<span class="string">"$first"</span>:<span class="string">"$_id"</span>&#125;&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#例4：求每个部门的总工资</span></span><br><span class="line">db.emp.aggregate(&#123;<span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:<span class="string">"$post"</span>,<span class="string">"count"</span>:&#123;<span class="string">"$sum"</span>:<span class="string">"$salary"</span>&#125;&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#例5：求每个部门的人数</span></span><br><span class="line">seledt count(<span class="number">1</span>) <span class="keyword">as</span> count <span class="keyword">from</span> emp;</span><br><span class="line">db.emp.aggregate(&#123;<span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:<span class="string">"$post"</span>,<span class="string">"count"</span>:&#123;<span class="string">"$sum"</span>:<span class="number">1</span>&#125;&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#3、数组操作符</span></span><br><span class="line">&#123;<span class="string">"$addToSet"</span>:expr&#125;：不重复</span><br><span class="line">&#123;<span class="string">"$push"</span>:expr&#125;：重复</span><br><span class="line"></span><br><span class="line"><span class="comment">#例：查询岗位名以及各岗位内的员工姓名:select post,group_concat(name) from db1.emp group by post;</span></span><br><span class="line">db.emp.aggregate(&#123;<span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:<span class="string">"$post"</span>,<span class="string">"names"</span>:&#123;<span class="string">"$push"</span>:<span class="string">"$name"</span>&#125;&#125;&#125;)</span><br><span class="line"><span class="comment"># 跟上面一样</span></span><br><span class="line">db.emp.aggregate(&#123;<span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:<span class="string">"$post"</span>,<span class="string">"names"</span>:&#123;<span class="string">"$addToSet"</span>:<span class="string">"$name"</span>&#125;&#125;&#125;)</span><br></pre></td></tr></table></figure>

<p>排序$sort  限制 $limit 跳过 $skip</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line">&#123;<span class="string">"$sort"</span>:&#123;<span class="string">"字段名"</span>:<span class="number">1</span>,<span class="string">"字段名"</span>:<span class="number">-1</span>&#125;&#125; <span class="comment">#1升序，-1降序</span></span><br><span class="line">&#123;<span class="string">"$limit"</span>:n&#125; </span><br><span class="line">&#123;<span class="string">"$skip"</span>:n&#125; <span class="comment">#跳过多少个文档</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#例1、取平均工资最高的前两个部门</span></span><br><span class="line">db.emp.aggregate(</span><br><span class="line">&#123;</span><br><span class="line">    <span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:<span class="string">"$post"</span>,<span class="string">"平均工资"</span>:&#123;<span class="string">"$avg"</span>:<span class="string">"$salary"</span>&#125;&#125;</span><br><span class="line">&#125;,</span><br><span class="line">&#123;</span><br><span class="line">    <span class="string">"$sort"</span>:&#123;<span class="string">"平均工资"</span>:<span class="number">-1</span>&#125;</span><br><span class="line">&#125;,</span><br><span class="line">&#123;</span><br><span class="line">    <span class="string">"$limit"</span>:<span class="number">2</span></span><br><span class="line">&#125;</span><br><span class="line">)</span><br><span class="line"><span class="comment">#例2、</span></span><br><span class="line">db.emp.aggregate(</span><br><span class="line">&#123;</span><br><span class="line">    <span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:<span class="string">"$post"</span>,<span class="string">"平均工资"</span>:&#123;<span class="string">"$avg"</span>:<span class="string">"$salary"</span>&#125;&#125;</span><br><span class="line">&#125;,</span><br><span class="line">&#123;</span><br><span class="line">    <span class="string">"$sort"</span>:&#123;<span class="string">"平均工资"</span>:<span class="number">-1</span>&#125;</span><br><span class="line">&#125;,</span><br><span class="line">&#123;</span><br><span class="line">    <span class="string">"$limit"</span>:<span class="number">3</span></span><br><span class="line">&#125;,</span><br><span class="line">&#123;</span><br><span class="line">    <span class="string">"$skip"</span>:<span class="number">1</span></span><br><span class="line">&#125;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line">db.emp.aggregate(</span><br><span class="line">&#123;</span><br><span class="line">    <span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:<span class="string">"$post"</span>,<span class="string">"平均工资"</span>:&#123;<span class="string">"$avg"</span>:<span class="string">"$salary"</span>&#125;&#125;</span><br><span class="line">&#125;,</span><br><span class="line">&#123;</span><br><span class="line">    <span class="string">"$sort"</span>:&#123;<span class="string">"平均工资"</span>:<span class="number">-1</span>&#125;</span><br><span class="line">&#125;,</span><br><span class="line">  &#123;</span><br><span class="line">    <span class="string">"$skip"</span>:<span class="number">2</span></span><br><span class="line">&#125;,</span><br><span class="line">&#123;</span><br><span class="line">    <span class="string">"$limit"</span>:<span class="number">2</span></span><br><span class="line">&#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<p>随机选取 $sample</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#集合users包含的文档如下</span></span><br><span class="line">db.users.insertMany([</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">1</span>, <span class="string">"name"</span> : <span class="string">"dave123"</span>, <span class="string">"q1"</span> : true, <span class="string">"q2"</span> : true &#125;,</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">2</span>, <span class="string">"name"</span> : <span class="string">"dave2"</span>, <span class="string">"q1"</span> : false, <span class="string">"q2"</span> : false  &#125;,</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">3</span>, <span class="string">"name"</span> : <span class="string">"ahn"</span>, <span class="string">"q1"</span> : true, <span class="string">"q2"</span> : true  &#125;,</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">4</span>, <span class="string">"name"</span> : <span class="string">"li"</span>, <span class="string">"q1"</span> : true, <span class="string">"q2"</span> : false  &#125;,</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">5</span>, <span class="string">"name"</span> : <span class="string">"annT"</span>, <span class="string">"q1"</span> : false, <span class="string">"q2"</span> : true  &#125;,</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">6</span>, <span class="string">"name"</span> : <span class="string">"li"</span>, <span class="string">"q1"</span> : true, <span class="string">"q2"</span> : true  &#125;,</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">7</span>, <span class="string">"name"</span> : <span class="string">"ty"</span>, <span class="string">"q1"</span> : false, <span class="string">"q2"</span> : true  &#125;</span><br><span class="line"></span><br><span class="line">])</span><br><span class="line"></span><br><span class="line"><span class="comment">#下述操作时从users集合中随机选取3个文档</span></span><br><span class="line"><span class="comment"># 抽奖</span></span><br><span class="line">db.users.aggregate(</span><br><span class="line">   [ &#123; $sample: &#123; size: <span class="number">1</span> &#125; &#125; ]</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 路飞项目搞活动，送优惠券---》3天后开奖---》100---》抽奖成功</span></span><br></pre></td></tr></table></figure>





<h2 id="六-Pymongo"><a href="#六-Pymongo" class="headerlink" title="六 Pymongo"></a>六 Pymongo</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">#https://api.mongodb.com/python/current/tutorial.html</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> pymongo <span class="keyword">import</span> MongoClient</span><br><span class="line"></span><br><span class="line"><span class="comment">#1、链接</span></span><br><span class="line">client=MongoClient(<span class="string">'mongodb://root:123@localhost:27017/'</span>)</span><br><span class="line"><span class="comment"># client = MongoClient('localhost', 27017)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#2、use 数据库</span></span><br><span class="line">db=client[<span class="string">'db2'</span>] <span class="comment">#等同于：client.db1</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#3、查看库下所有的集合</span></span><br><span class="line">print(db.collection_names(include_system_collections=<span class="literal">False</span>))</span><br><span class="line"></span><br><span class="line"><span class="comment">#4、创建集合</span></span><br><span class="line">table_user=db[<span class="string">'userinfo'</span>] <span class="comment">#等同于：db.user</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#5、插入文档</span></span><br><span class="line"><span class="keyword">import</span> datetime</span><br><span class="line">user0=&#123;</span><br><span class="line">    <span class="string">"_id"</span>:<span class="number">1</span>,</span><br><span class="line">    <span class="string">"name"</span>:<span class="string">"egon"</span>,</span><br><span class="line">    <span class="string">"birth"</span>:datetime.datetime.now(),</span><br><span class="line">    <span class="string">"age"</span>:<span class="number">10</span>,</span><br><span class="line">    <span class="string">'hobbies'</span>:[<span class="string">'music'</span>,<span class="string">'read'</span>,<span class="string">'dancing'</span>],</span><br><span class="line">    <span class="string">'addr'</span>:&#123;</span><br><span class="line">        <span class="string">'country'</span>:<span class="string">'China'</span>,</span><br><span class="line">        <span class="string">'city'</span>:<span class="string">'BJ'</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">user1=&#123;</span><br><span class="line">    <span class="string">"_id"</span>:<span class="number">2</span>,</span><br><span class="line">    <span class="string">"name"</span>:<span class="string">"alex"</span>,</span><br><span class="line">    <span class="string">"birth"</span>:datetime.datetime.now(),</span><br><span class="line">    <span class="string">"age"</span>:<span class="number">10</span>,</span><br><span class="line">    <span class="string">'hobbies'</span>:[<span class="string">'music'</span>,<span class="string">'read'</span>,<span class="string">'dancing'</span>],</span><br><span class="line">    <span class="string">'addr'</span>:&#123;</span><br><span class="line">        <span class="string">'country'</span>:<span class="string">'China'</span>,</span><br><span class="line">        <span class="string">'city'</span>:<span class="string">'weifang'</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment"># res=table_user.insert_many([user0,user1]).inserted_ids</span></span><br><span class="line"><span class="comment"># print(res)</span></span><br><span class="line"><span class="comment"># print(table_user.count())</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#6、查找</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># from pprint import pprint#格式化细</span></span><br><span class="line"><span class="comment"># pprint(table_user.find_one())</span></span><br><span class="line"><span class="comment"># for item in table_user.find():</span></span><br><span class="line"><span class="comment">#     pprint(item)</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># print(table_user.find_one(&#123;"_id":&#123;"$gte":1&#125;,"name":'egon'&#125;))</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#7、更新</span></span><br><span class="line">table_user.update(&#123;<span class="string">'_id'</span>:<span class="number">1</span>&#125;,&#123;<span class="string">'name'</span>:<span class="string">'EGON'</span>&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">#8、传入新的文档替换旧的文档</span></span><br><span class="line">table_user.save(</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="string">"_id"</span>:<span class="number">2</span>,</span><br><span class="line">        <span class="string">"name"</span>:<span class="string">'egon_xxx'</span></span><br><span class="line">    &#125;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># pip3 install pymong</span></span><br><span class="line"><span class="keyword">from</span> pymongo <span class="keyword">import</span> MongoClient</span><br><span class="line"><span class="keyword">from</span> pymongo.collection <span class="keyword">import</span> Collection</span><br><span class="line"><span class="comment">#MongoClient('mongodb://root:123@localhost:27017/')</span></span><br><span class="line">conn=MongoClient(host=<span class="string">"10.0.0.5"</span>,port=<span class="number">27017</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># use lqz</span></span><br><span class="line"><span class="comment"># 你用过python中的魔法方法(init,new,str) __add__</span></span><br><span class="line"><span class="comment"># with  __enter__  __exit__</span></span><br><span class="line"></span><br><span class="line">lqz=conn.lqz  <span class="comment"># 重写了__getattr__</span></span><br><span class="line"><span class="comment"># lqz=conn["lqz"] # 重写了__getitem__</span></span><br><span class="line"><span class="comment">#lqz.users 获取表</span></span><br><span class="line">users=lqz.users <span class="comment"># type:Collection</span></span><br><span class="line"><span class="comment"># users.find(&#123;'name':"li"&#125;)</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># users.insert_many()</span></span><br><span class="line"><span class="comment"># users.insert_one()</span></span><br><span class="line"><span class="comment"># update被弃用了</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># users.update()</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># users.aggregate(&#123;&#125;,&#123;&#125;,&#123;&#125;)</span></span><br><span class="line"><span class="comment"># users.delete_many()</span></span><br><span class="line"><span class="comment"># users.delete_one()</span></span><br><span class="line"><span class="comment"># print(users.find())</span></span><br><span class="line"><span class="comment"># for i in users.find(&#123;'name':"li"&#125;):</span></span><br><span class="line"><span class="comment">#     print(type(i))</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">#集成到django框架和flask框架</span></span><br></pre></td></tr></table></figure>

<h2 id="七-练习题"><a href="#七-练习题" class="headerlink" title="七 练习题"></a>七 练习题</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span> 查询岗位名以及各岗位内的员工姓名</span><br><span class="line"><span class="number">2.</span> 查询岗位名以及各岗位内包含的员工个数</span><br><span class="line"><span class="number">3.</span> 查询公司内男员工和女员工的个数</span><br><span class="line"><span class="number">4.</span> 查询岗位名以及各岗位的平均薪资、最高薪资、最低薪资</span><br><span class="line"><span class="number">5.</span> 查询男员工与男员工的平均薪资，女员工与女员工的平均薪资</span><br><span class="line"><span class="number">6.</span> 查询各岗位内包含的员工个数小于<span class="number">2</span>的岗位名、岗位内包含员工名字、个数</span><br><span class="line"><span class="number">7.</span> 查询各岗位平均薪资大于<span class="number">10000</span>的岗位名、平均工资</span><br><span class="line"><span class="number">8.</span> 查询各岗位平均薪资大于<span class="number">10000</span>且小于<span class="number">20000</span>的岗位名、平均工资</span><br><span class="line"><span class="number">9.</span> 查询所有员工信息，先按照age升序排序，如果age相同则按照hire_date降序排序</span><br><span class="line"><span class="number">10.</span> 查询各岗位平均薪资大于<span class="number">10000</span>的岗位名、平均工资,结果按平均薪资升序排列</span><br><span class="line"><span class="number">11.</span> 查询各岗位平均薪资大于<span class="number">10000</span>的岗位名、平均工资,结果按平均薪资降序排列,取前<span class="number">1</span>个</span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span> 查询岗位名以及各岗位内的员工姓名</span><br><span class="line">db.emp.aggregate(&#123;<span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:<span class="string">"$post"</span>,<span class="string">"names"</span>:&#123;<span class="string">"$push"</span>:<span class="string">"$name"</span>&#125;&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="number">2.</span> 查询岗位名以及各岗位内包含的员工个数</span><br><span class="line">db.emp.aggregate(&#123;<span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:<span class="string">"$post"</span>,<span class="string">"count"</span>:&#123;<span class="string">"$sum"</span>:<span class="number">1</span>&#125;&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="number">3.</span> 查询公司内男员工和女员工的个数</span><br><span class="line">db.emp.aggregate(&#123;<span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:<span class="string">"$sex"</span>,<span class="string">"count"</span>:&#123;<span class="string">"$sum"</span>:<span class="number">1</span>&#125;&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="number">4.</span> 查询岗位名以及各岗位的平均薪资、最高薪资、最低薪资</span><br><span class="line">db.emp.aggregate(&#123;<span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:<span class="string">"$post"</span>,<span class="string">"avg_salary"</span>:&#123;<span class="string">"$avg"</span>:<span class="string">"$salary"</span>&#125;,<span class="string">"max_salary"</span>:&#123;<span class="string">"$max"</span>:<span class="string">"$salary"</span>&#125;,<span class="string">"min_salary"</span>:&#123;<span class="string">"$min"</span>:<span class="string">"$salary"</span>&#125;&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="number">5.</span> 查询男员工与男员工的平均薪资，女员工与女员工的平均薪资</span><br><span class="line">db.emp.aggregate(&#123;<span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:<span class="string">"$sex"</span>,<span class="string">"avg_salary"</span>:&#123;<span class="string">"$avg"</span>:<span class="string">"$salary"</span>&#125;&#125;&#125;)</span><br><span class="line"></span><br><span class="line"><span class="number">6.</span> 查询各岗位内包含的员工个数小于<span class="number">2</span>的岗位名、岗位内包含员工名字、个数</span><br><span class="line">db.emp.aggregate(</span><br><span class="line">&#123;</span><br><span class="line">    <span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:<span class="string">"$post"</span>,<span class="string">"count"</span>:&#123;<span class="string">"$sum"</span>:<span class="number">1</span>&#125;,<span class="string">"names"</span>:&#123;<span class="string">"$push"</span>:<span class="string">"$name"</span>&#125;&#125;</span><br><span class="line">&#125;,</span><br><span class="line">&#123;<span class="string">"$match"</span>:&#123;<span class="string">"count"</span>:&#123;<span class="string">"$lt"</span>:<span class="number">2</span>&#125;&#125;&#125;,</span><br><span class="line">&#123;<span class="string">"$project"</span>:&#123;<span class="string">"_id"</span>:<span class="number">0</span>,<span class="string">"names"</span>:<span class="number">1</span>,<span class="string">"count"</span>:<span class="number">1</span>&#125;&#125;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="number">7.</span> 查询各岗位平均薪资大于<span class="number">10000</span>的岗位名、平均工资</span><br><span class="line">db.emp.aggregate(</span><br><span class="line">&#123;</span><br><span class="line">    <span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:<span class="string">"$post"</span>,<span class="string">"avg_salary"</span>:&#123;<span class="string">"$avg"</span>:<span class="string">"$salary"</span>&#125;&#125;</span><br><span class="line">&#125;,</span><br><span class="line">&#123;<span class="string">"$match"</span>:&#123;<span class="string">"avg_salary"</span>:&#123;<span class="string">"$gt"</span>:<span class="number">10000</span>&#125;&#125;&#125;,</span><br><span class="line">&#123;<span class="string">"$project"</span>:&#123;<span class="string">"_id"</span>:<span class="number">1</span>,<span class="string">"avg_salary"</span>:<span class="number">1</span>&#125;&#125;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="number">8.</span> 查询各岗位平均薪资大于<span class="number">10000</span>且小于<span class="number">20000</span>的岗位名、平均工资</span><br><span class="line">db.emp.aggregate(</span><br><span class="line">&#123;</span><br><span class="line">    <span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:<span class="string">"$post"</span>,<span class="string">"avg_salary"</span>:&#123;<span class="string">"$avg"</span>:<span class="string">"$salary"</span>&#125;&#125;</span><br><span class="line">&#125;,</span><br><span class="line">&#123;<span class="string">"$match"</span>:&#123;<span class="string">"avg_salary"</span>:&#123;<span class="string">"$gt"</span>:<span class="number">10000</span>,<span class="string">"$lt"</span>:<span class="number">20000</span>&#125;&#125;&#125;,</span><br><span class="line">&#123;<span class="string">"$project"</span>:&#123;<span class="string">"_id"</span>:<span class="number">1</span>,<span class="string">"avg_salary"</span>:<span class="number">1</span>&#125;&#125;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="number">9.</span> 查询所有员工信息，先按照age升序排序，如果age相同则按照hire_date降序排序</span><br><span class="line">db.emp.aggregate(</span><br><span class="line">&#123;<span class="string">"$sort"</span>:&#123;<span class="string">"age"</span>:<span class="number">1</span>,<span class="string">"hire_date"</span>:<span class="number">-1</span>&#125;&#125;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="number">10.</span> 查询各岗位平均薪资大于<span class="number">10000</span>的岗位名、平均工资,结果按平均薪资升序排列</span><br><span class="line">db.emp.aggregate(</span><br><span class="line">&#123;</span><br><span class="line">    <span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:<span class="string">"$post"</span>,<span class="string">"avg_salary"</span>:&#123;<span class="string">"$avg"</span>:<span class="string">"$salary"</span>&#125;&#125;</span><br><span class="line">&#125;,</span><br><span class="line">&#123;<span class="string">"$match"</span>:&#123;<span class="string">"avg_salary"</span>:&#123;<span class="string">"$gt"</span>:<span class="number">10000</span>&#125;&#125;&#125;,</span><br><span class="line">&#123;<span class="string">"$sort"</span>:&#123;<span class="string">"avg_salary"</span>:<span class="number">1</span>&#125;&#125;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="number">11.</span> 查询各岗位平均薪资大于<span class="number">10000</span>的岗位名、平均工资,结果按平均薪资降序排列,取前<span class="number">1</span>个</span><br><span class="line">db.emp.aggregate(</span><br><span class="line">&#123;</span><br><span class="line">    <span class="string">"$group"</span>:&#123;<span class="string">"_id"</span>:<span class="string">"$post"</span>,<span class="string">"avg_salary"</span>:&#123;<span class="string">"$avg"</span>:<span class="string">"$salary"</span>&#125;&#125;</span><br><span class="line">&#125;,</span><br><span class="line">&#123;<span class="string">"$match"</span>:&#123;<span class="string">"avg_salary"</span>:&#123;<span class="string">"$gt"</span>:<span class="number">10000</span>&#125;&#125;&#125;,</span><br><span class="line">&#123;<span class="string">"$sort"</span>:&#123;<span class="string">"avg_salary"</span>:<span class="number">-1</span>&#125;&#125;,</span><br><span class="line">&#123;<span class="string">"$limit"</span>:<span class="number">1</span>&#125;,</span><br><span class="line">&#123;<span class="string">"$project"</span>:&#123;<span class="string">"date"</span>:new Date,<span class="string">"平均工资"</span>:<span class="string">"$avg_salary"</span>,<span class="string">"_id"</span>:<span class="number">0</span>&#125;&#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

</section>
    <!-- Tags START -->
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/go/7-%E5%85%B6%E4%BB%96/06-go-get-golang.org:x-%E5%8C%85%E5%A4%B1%E8%B4%A5/">
        <span class="nav-arrow">← </span>
        
          06-go get golang.org/x 包失败
        
      </a>
    
    
      <a class="nav-right" href="/linux/%E5%85%A5%E9%97%A8%E5%88%B0%E7%B2%BE%E9%80%9A/02-Linux%E7%B3%BB%E7%BB%9F%E5%AE%89%E8%A3%85/">
        
          02-Linux系统安装
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
      <div class="money-like">
        <div class="reward-btn">
          赏
          <span class="money-code">
            <span class="alipay-code">
              <div class="code-image"></div>
              <b>使用支付宝打赏</b>
            </span>
            <span class="wechat-code">
              <div class="code-image"></div>
              <b>使用微信打赏</b>
            </span>
          </span>
        </div>
        <p class="notice">点击上方按钮,请我喝杯咖啡！</p>
      </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- Gitment START -->
      <div id="comments"></div>
      <!-- Gitment END -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
  <!-- 不蒜子统计 -->
    <strong class="toc-title">目录</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#Mongodb"><span class="toc-nav-text">Mongodb</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#一-简介"><span class="toc-nav-text">一 简介</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#1-1-易用性"><span class="toc-nav-text">1.1 易用性</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#1-2-易扩展性"><span class="toc-nav-text">1.2 易扩展性</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#1-3-丰富的功能"><span class="toc-nav-text">1.3 丰富的功能</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#1-4、卓越的性能"><span class="toc-nav-text">1.4、卓越的性能</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#二-MongoDB基础知识"><span class="toc-nav-text">二 MongoDB基础知识</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#2-1-文档是MongoDB的核心概念。文档就是键值对的一个有序集-‘msg’-’hello’-’foo’-3-。类似于python中的有序字典。"><span class="toc-nav-text">2.1 文档是MongoDB的核心概念。文档就是键值对的一个有序集{‘msg’:’hello’,’foo’:3}。类似于python中的有序字典。</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#2-2-集合就是一组文档。如果将MongoDB中的一个文档比喻为关系型数据的一行，那么一个集合就是相当于一张表"><span class="toc-nav-text">2.2 集合就是一组文档。如果将MongoDB中的一个文档比喻为关系型数据的一行，那么一个集合就是相当于一张表</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#2-3-数据库：在MongoDB中，多个文档组成集合，多个集合可以组成数据库"><span class="toc-nav-text">2.3 数据库：在MongoDB中，多个文档组成集合，多个集合可以组成数据库</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#2-4-强调：把数据库名添加到集合名前，得到集合的完全限定名，即命名空间"><span class="toc-nav-text">2.4 强调：把数据库名添加到集合名前，得到集合的完全限定名，即命名空间</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#三-安装-amp-配置"><span class="toc-nav-text">三 安装&amp;配置</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#3-1-安装"><span class="toc-nav-text">3.1 安装</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#3-2-账号管理"><span class="toc-nav-text">3.2 账号管理</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#四-基本数据类型"><span class="toc-nav-text">四 基本数据类型</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#五-CURD操作"><span class="toc-nav-text">五 CURD操作</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#5-1-数据库操作"><span class="toc-nav-text">5.1 数据库操作</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#5-2-集合操作（表）"><span class="toc-nav-text">5.2 集合操作（表）</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#5-3-文档操作"><span class="toc-nav-text">5.3 文档操作</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#5-3-1-新增文档"><span class="toc-nav-text">5.3.1 新增文档</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#5-3-2-查询文档"><span class="toc-nav-text">5.3.2 查询文档</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#5-3-3-修改文档"><span class="toc-nav-text">5.3.3 修改文档</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#5-3-4-删除文档"><span class="toc-nav-text">5.3.4 删除文档</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#5-3-5-聚合"><span class="toc-nav-text">5.3.5 聚合</span></a></li></ol></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#六-Pymongo"><span class="toc-nav-text">六 Pymongo</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#七-练习题"><span class="toc-nav-text">七 练习题</span></a></li></ol></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'http://www.liuqingzheng.top/db/Mongodb系列/Mongodb快速入门/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


  <script>
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });
  </script>



  <script>
    var gitmentConfig = "liuqingzheng";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "db/Mongodb系列/Mongodb快速入门",
        owner: "liuqingzheng",
        repo: "FuckBlog",
        oauth: {
          client_id: "32a4076431cf39d0ecea",
          client_secret: "94484bd79b3346a949acb2fda3c8a76ce16990c6"
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  </script>




    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
<!-- 不蒜子统计 -->
<span id="busuanzi_container_site_pv">
     本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<span class="post-meta-divider">|</span>
<span id="busuanzi_container_site_uv" style='display:none'>
     本站访客数<span id="busuanzi_value_site_uv"></span>人
</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



  <p class="copyright">
    &copy; 2021 | Proudly powered by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank">小猿取经</a>
    <br>
    Theme by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank" rel="noopener">小猿取经</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>





<!-- Baidu Tongji -->

<script>
    var _baId = 'c5fd96eee1193585be191f318c3fa725';
    // Originial
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?" + _baId;
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
</script>


<script src="/js/script.js"></script>


<script src="/js/search.js"></script>


<script src="/js/load.js"></script>



  <span class="local-search local-search-google local-search-plugin" style="right: 50px;top: 70px;;position:absolute;z-index:2;">
      <input type="search" placeholder="站内搜索" id="local-search-input" class="local-search-input-cls" style="">
      <div id="local-search-result" class="local-search-result-cls"></div>
  </span>


  </body>
</html>